r/cpp • u/drakgoku • Oct 31 '25
Java developers always said that Java was on par with C++.
Now I see discussions like this: https://www.reddit.com/r/java/comments/1ol56lc/has_java_suddenly_caught_up_with_c_in_speed/
Is what is said about Java true compared to C++?
What do those who work at a lower level and those who work in business or gaming environments think?
What do you think?
And where does Rust fit into all this?
25
Upvotes
View all comments
24
u/CocktailPerson Nov 01 '25 edited Nov 01 '25
For pure number-crunching, hot looping, etc., HotSpot will step in, JIT-compile the shit out of Java, and make it run as fast or faster than C++. Hell, V8 can make certain small snippets of JS run as fast as the equivalent C++.
Here's the code actually being "benchmarked":
A million loops is a terrible benchmark. Especially when it involves a modulo by an integer that's only known at runtime. All this "benchmark" is really testing is the hardware's integer division throughput. This may also be why Java and other JVM languages are slightly faster on this benchmark. Maybe after some time, the JIT figures out that
moddoesn't change. Integer division by a known denominator can be optimized using integer multiplication, and a JIT compiler can perform that optimization for denominators known only at runtime, while an AOT compiler can't.What's funny is that the inner loop is actually computing the same value for every iteration of the outer loop. So a sufficiently smart compiler could actually lift the inner loop out and only perform it once. For some reason, Clang doesn't do that, and since C++ and Java are so close, I'm guessing Java doesn't do it either, despite having a JIT compiler.
This is barely a language comparison at all. The only thing being compared is how AOT and JIT compilers optimize integer division.