Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get a Java program faster than the same program (optimized) in C? [closed]

Regarding the fact that C/C++ optimization are produced at compilation time, and Java optimizations are produced at runtime. Is it possible to get a Java program faster than the same program (optimized) in C?

I understand that runtime optimizations can be better than compilation time. Hence I am wondering if the gain of these optimization can be compared to the overhead of running the JVM.

like image 697
Antonio Avatar asked Sep 12 '13 09:09

Antonio


1 Answers

In theory, yes. In practice, it is highly unlikely.

One of the fundamental assumption is that C/C++ is compiled once for a binary opcode target, and that Java is compiled for the specific machine it is running on. This should give an edge to Java. But the reality is that even C/C++ can have several optimization path, dynamically selected at run time, and get most of the benefit of specific-target compilation.

Conversely, as stated by Rekin, the Java JVM needs to dynamically profile the Java program to know what to optimize and how. Profiling is an expensive operation in itself, and that overhead can't be taken off Java JVM. On the other hand, selecting the right set of optimization for the current workload can give an edge. In practice, most C programs (but not all :) are well tuned for their task, and there is little left to optimize using profiling techniques.

There are other effects in Java which completely dwarf these compilation issues. Probably at first position is the Garbage Collector.

Garbage collector first mission is to ease programming, take care of, and avoiding one of the most nasty recurrent bug of C/C++, memory leaks. This feature alone justify the large use of Java in many industrial environment.

However, it has a cost. A very large one. According to studies, it is necessary to have available about 5x the amount of strictly necessary memory to make sure garbage collector works with minimal overhead. So, whenever such amount of memory is lacking, GC overhead starts to become significant, putting performance to a crawl.

Adversely, it may happen, in some circumstances, that freeing the algorithm of memory allocation charge may allow to change the algorithm, and adopt a better, faster one. In such a circumstance, Java can get the edge, and be faster than a C program.

But as you can guess, this is uncommon...

like image 166
Cyan Avatar answered Sep 29 '22 07:09

Cyan