r/learnjava • • Nov 03 '20

Why is c faster than java?

If I were to make the same thing in java would it now be as fast ?

58 Upvotes

26 comments sorted by

View all comments

66

u/gtrley Nov 03 '20

Something along the lines of C is a lower level language and runs closer to the hardware, considering Java runs in the JVM

7

u/IIwarrierII Nov 03 '20

But once java is compiled isn’t it fast ?

79

u/gtrley Nov 03 '20

Whoops thought i replied but made a whole new thread

Edit: pasted response below :)

Faster than python since you're running a pre-compiled program vs interpreted as you go, but C is going to be compiled specifically for the platform you run it on, where Java is more half-compiled, then the JVM does final translations to the platform

This is why Java is "write once run anywhere" and C is not. I.e. if i wanted to run a C program on say, a linux machine, then later decide I want to run it on windows, I would need to recompile it, where with Java I compile a .class file and I can run that on any system with a JVM

25

u/IIwarrierII Nov 03 '20

Thanks a lot I learnt a lot from you

11

u/gtrley Nov 03 '20

Happy to help! Im sure someone out there can go into much more granular detail than what I can provide lol, but that is my understanding of it :)

4

u/feral_claire Nov 04 '20

Well yes and no. The JVM will compile performance critical methods into optimized machine code. While this means at first it so run a bit slower, once compiled the code can be just as fast or even faster since it has the advantage of being and to use run time data to optimize the code. While it's true that Java programs tend to be a bit slower than a well optimized C program, its not a simple as Java bytecode being interpreted like python.

7

u/gtrley Nov 04 '20

I didnt say java code was interpreted like python?

2

u/feral_claire Nov 06 '20

Perhaps I misinterpreted your comment. When you wrote "JVM does final translations to the platform" I read that at "interpreting" which is not quite the full story. I can see now how that wording might have actually referred to the jit compilation as well.

5

u/__Ambition Nov 04 '20

Java compiles to bytecode. Bytecode is then run by a Virtual Machine which is roughly speaking, a software emulation of the CPU.

C on the other hand compiles to machine code, which runs on the actual CPU. Since Java's Virtual Machine software runs on top of the actual machine hardware, it's slower. C has no such software layer, it runs directly on hardware once compiled.

(Note that this an overly simplified explanation and things like JIT compilation make this a bit harder to ELY5.)