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

Show parent comments

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

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.