Is C++ faster than java?

363    Asked by alexGONZALEZ in Java , Asked on Oct 10, 2022

Sometimes Java outperforms C++ in benchmarks. Of course, sometimes C++ outperforms.


See the following links:


http://keithlea.com/javabench/

http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/

But how is this even possible? It boggles my mind that interpreted bytecode could ever be faster than a compiled language.


Can someone please explain?

Answered by ananya Pawar
  Your question- Is C++ faster than java can be answered as - 

All things being equal, you could say: no, Java should never be faster. You could always implement Java in C++ from scratch and thereby get at least as good performance. In practice, however: JIT compiles the code on the end-user's machine, allowing it to optimise for the exact CPU that they are running. While there's an overhead here for the compilation, it may well pay off for intensive apps. Often real life programs are not compiled for the CPU you are using.

The Java compiler may well be better at automatically optimising things than a C++ compiler. Or it may not, but in the real world, things aren't always perfect. Performance behaviour can vary due to other factors, such as garbage collection. In C++, you typically call the destructor immediately when done with an object. In Java, you simply release the reference, delaying the actual destruction. This is another example of a difference which is neither here nor there, in terms of performance. Of course, you can argue that you could implement GC in C++ and be done with it, but the reality is that few people do / want to / can.

As an aside, this reminds me of the debate regarding C in the 80s / 90s. Everyone was wondering "can C ever be as fast as assembly?". Basically, the answer was: no on paper, but in reality the C compiler created more efficient code than 90% of the assembly programmers (well, once it matured a bit).



Your Answer

Interviews

Parent Categories