Home / Language / English / Java vs. C++: The Performance Showdown

Java vs. C++: The Performance Showdown

Since the early days of the Java programming language, some have argued that Java’s being an interpreted language has made it inferior to the likes of C and C++ in terms of performance. Of course, C++ devotees would never, ever even consider Java a “proper” language, while the Java crowd always throws “write once, run everywhere” in the faces of the C++ programmers.

First things first, how well does Java perform when it comes to basic integer arithmetic? If I asked you how much 2 x 3 is, you would probably answer in no time. How long would it take a program? To check, here’s a basic test:

  1. Generate first X numbers of random integer numbers.
  2. Multiply those numbers with every number from 2 to Y.
  3. Compute how long it takes to perform the whole set.

Because you’re not interested in how long it takes to generate a random number, it is important that you generate the random numbers upfront, before you start measuring.


To compare: 25ms in Java, 0.001ms in C++. That’s quite a difference! However, bear in mind that the C++ code was compiled using full compiler and linker optimization for speed. Simply disabling the optimization will you return the following result:

C computing took 70.179901

Ouch! That is three times slower than the Java version! The moral of the story is: yes, C++ performs better at first glance, but (and this is a big but) only if the compiler optimizes the code well!

Most C++ compilers nowadays will perform a decent optimization of the generated code. However, the difference between 1/1000th of a millisecond and 70 milliseconds is left in the hands of the compiler. Always bear that in mind when you switch to C++ for speed reasons!


About Mohammad Khazab

%d bloggers like this: