1) Java's bytecodes are interpreted by a virtual machine, therefore Java can never be as fast as a statically compiled language such as C
2) Java's VM can perform dynamic optimization in ways not available to a statically optimizing C compiler, therefore Java can outperform C.
The web is full of opinions on which is the fastest language and why. There are plenty of benchmarks proving once and for all one view or the other. However, you never really believe it unless you've tried it yourself. So here, for the first time ever is conclusive proof that really there ain't much in it one way or another.
My completely unscientific test case: an algorithm to sum the first N Fibonacci numbers. The numbers themselves are calculated by a deliberately naive recursive algorithm - don't try this at home. The running time grows exponentially with N. However, it is easy to get a good range of running times. The algorithm can be coded almost identically, line for line, in my 3 target languages of Java, C, Python.
Here are the results:
N | Java (client vm) | Java (server vm) | C (gcc standard options) | C (gcc -O3) | Python |
---|---|---|---|---|---|
0 | 0.2 | 0.2 | 0 | 0 | 0 |
10 | 0.2 | 0.2 | 0 | 0 | 0 |
20 | 0.2 | 0.2 | 0 | 0 | 0 |
30 | 0.3 | 0.2 | 0 | 0 | 1.4 |
35 | 0.5 | 0.4 | 0.2 | 15 | |
40 | 2.5 | 4.8 | 1.8 | 171 | |
45* | 24.5 | 20.6 | 52 | 19.8 | |
50 | 272 | 232 | 600 | 227 |
*For N>=45 the result overflows when using 32 bit integers. Here's some results using Java longs and C long longs (64 bits):
N | Java (server vm) | C (gcc -O3) |
---|---|---|
45 | 21 | 23.5 |
50 | 221 | 265 |
No doubt you can find algorithms (and better C compilers) that change the results. But change them enough for you to care?
Details:
The tests were run on Ubuntu Linux running in a Parallels VM on a 2007 model Macbook Pro with a couple of gig of RAM.
The Java code was compiled and run with Java 6, the C code with gcc, and the Python code run with Python 2.4.3
Times are the sum of user and system time in secs, recorded to the nearest 0.1 of a sec, and the tests were run a handful of times until I reckoned the time looked about right. Times include any VM startup times.