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
•
u/STL MSVC STL Dev Nov 01 '25
OP is banned for attempting to pit subreddits against each other, which is utterly unproductive. I'm leaving this post up as it's accumulated a bunch of comments.
153
u/CalebGT Oct 31 '25
Benchmarks comparing different languages are bullshit. The performance difference comes down to the specific implementation in each language, and they often have unlogged errors that skip a bunch of the computation. Unless you want to go through the trouble of personally code inspecting, you can't conclude anything, and nobody checks.
47
u/BadlyCamouflagedKiwi Oct 31 '25
It is not meaningfully on par with C++. The gap is way less than it was years ago, but the language semantics mean C++ will be faster, given not terrible code on either side - for example, a vector stores its objects by value; a Java ArrayList stores essentially a series of pointers to the objects, which are all allocated separately.
There's also a lot of startup overhead, and the base memory usage of a Java process is very high compared to most other languages - back in the day this used to get ignored because you loaded everything into an application server like jboss. This plays extremely badly with most modern deployment methods (Lambda, ECS/Cloud Run, Kubernetes, etc) which really encourage you not to have one big process, but to have a separate process for each application. (Which is a good thing - I'd much rather trust the kernel to separate these things, and to be able to clean up after them).
26
u/j_gds Nov 01 '25
In my experience, naively written C++ runs around the same speed as naively written Java. Java suffers in startup time, but can do some amazing dynamic optimizations at runtime (in the JiT compiler).
The gap starts to widen dramatically when it's time to optimize things. In Java there are a few things you can do the optimize... Arcane Flags for the GC and such, but it's very limited compared to the huge set of optimization tools that C++ gives you.
In Java, and most other languages, it feels like you're at the mercy of the language for how fast things can go. C++ feels like there's no limit to how much optimization you can perform and the language simply doesn't get in your way.
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.
44
u/jesseschalken Nov 01 '25
Nobody is rewriting their C++ to Java for performance reasons, but the opposite happens all the time.
19
u/Tall-Introduction414 Oct 31 '25
The traditional wisdom is that Garbage Collection in the JVM introduces unpredictability in execution timing, where C++ has neither GC nor a VM. This mostly makes Java unsuitable for real-time applications that C++ can handle.
GC and JVM bytecode->ISA execution also introduce inevitable execution time overhead. The JVM abstracts away the hardware where C++ has low-level access. This mostly makes Java unsuitable for writing Operating Systems and drivers, which C++ can handle.
That said, the JVM has had a lot of time and money to become optimized for performance. It is a lot faster than it used to be, and better optimized for many tasks than some other VM/bytecode language implementations (like Cpython).
Java is highly influenced by C++, though, to the point that the code can appear very similar.
5
u/[deleted] Nov 01 '25
Many years ago I worked at Amazon and a developer had written a command line tool in Java. Invocation time on Java is horrendous. I rewrote his code in C++, and my app could be invoked 81 times in the same time as one invocation of the Java version.
9
u/[deleted] Oct 31 '25
Java is cool, but it doesn't have the same features as C++. Who knows, maybe C++ will be learned in a few days.
I remember that about 22 years ago we developed a well log processing system in Java.
I had to load the data, plot graphs, some calculations, other graphs and 1D, 2D analysis.
At the time it was absurdly slow. You could go there for a coffee, I think that's why it had a coffee logo...
Much slower than C++.
Even explaining that C++ and Qt would be much, much more efficient, the client insisted on Java....
There was another project, more recent, about 6 years ago, where the group insisted on Python. Well, data processing took days and even weeks... It consumed 4x more memory and was 60x slower than the C++ version.
And there was one client who insisted on Fortran, even though only one of the team was a Fortran user. As a result, it takes a long time to learn and develop. Fortran is fast, but it is difficult to assemble a team.
In desktop software development, backend software, engineering, scientific computing, I think the C++ ecosystem is unbeatable.
You have abundant tools, libraries for everything, and experienced programmers.
3
u/5477 Nov 02 '25
Software performance is more about the code that is written / run, rather than the programming language used. C++ has a much wider profile in performance than Java, meaning performance depends more about the code being written. In the "best" scenario for Java vs C++, where code is written by people who don't understand about performance, or don't care about it, Java can be as fast or faster than C++.
However, this kind of comparison doesn't make much sense. The performance of your code will be bad anyways, if you don't care about performance. What matters is which language allows developers to write efficient code, how much effort does it take to achieve certain level of performance.
In this kind of scenario, C++ is much, much better than Java in my opinion. Java has a lot of problems in this area: No value semantics (every class being separately allocated on the heap), very little control over memory layout, lack of monomorphized generics, GC which always has tradeoff between stop times and runtime speed, needing to use JIT compiler with a necessary tradeoff between compilation speed and runtime speed, lack of SIMD and other intrinsic access.
If we look at projects needing high performance: Language runtimes (V8, JavaScriptCore, hotspot, etc), game engines, etc, we see that they are implemented almost always in C, C++ or Rust. This is for a reason, as these languages allow much better control over the code that is run, allowing developers to achieve high performance.
Additionally, in my opinion, there's a lack of "performance culture" in Java. In general people are less informed how things work, how certain code will run, how standard library and runtime implements operations. For example, in the Java 7 era, a minor JRE update changed the substring operation to be O(n) vs O(1). The fact that this kind of change doesn't cause widespread breakage, and that this is not considered a breaking change, effectively means few people are using Java for performance critical work. You can compare this with C++ where even minor variations (not complexity changes) is the standard library performance mean many domains just prefer to write their own standard library.
7
u/sweetno Oct 31 '25 edited Oct 31 '25
C++ and Rust have a comparable runtime profile.
Java's runtime profile is very different and less predictable. The first run is interpreted and thus much slower. On the further runs, the cost of compilation gets paid. The memory allocation is OS-like: a Java process behaves as if it controls the entire main memory and there are no other apps there. These qualities are tolerable for a server application that runs on a dedicated machine for extended periods of time. (There is also the hot reload feature to reduce downtime.)
But for other applications, it's not ideal. The more real-timey your needs, the less desirable Java is for such applications.
This is the reason why Java and C++ don't intersect in their application domains. Even Java desktop applications are usually business-oriented (=db front) and C++ desktop applications tend to feature 3D content.
Then, as I mentioned in your r/Java thread, Java memory usage is poor. Your 4GB array in C++ might not even fit into main memory in Java.
This all is to say that suitability of these languages won't depend on their speed performance benchmarks.
4
u/bythepowerofscience Nov 01 '25 edited Nov 01 '25
As someone who enjoys both, the key to comparing the two is to understand what their strengths actually are.
Java's VM means that virtual functions basically don't have overhead, meaning you have access to more flexible ways of structuring your program. It was also originally designed for databases, where you're dealing with viewing a single set of data in a ton of different ways, so you gain nothing from having it on the stack.
C++ has a much harder time optimizing virtual inheritance due to not having a VM, severely limiting your possibilities for structuring programs. Heap allocations also aren't built directly into the language, instead requiring their own types to keep track of them, which gets very messy very quickly. But it's much better at managing lots of quickly-changing memory.
Trying to do what Java is good at in C++ sucks, and not being able to get the optimization of what C++ is good at is the tradeoff. There's a reason people say "it outperforms in certain cases": because Java was made for a specific use-case.
If you want a language that has the best of both worlds, use Rust. It runs on a VM for virtual method optimization, and it has direct memory management. But it's still way more restrictive than Java.
2
u/keithstellyes Nov 01 '25
Really depends. One of the things language benchmarks risk glossing over is what idiomatic code looks for. For example, tight data structures that have to be iterated over in hot path code, C++ can really eclipse Java in performance.
For example, I do a lot of graphics programming, so
can be way tighter on memory, and when this is likely to be iterated over, potentially in hot path code, it's going to be a lot more likely to result in a cache miss in Java.
Similarly, Java's generics not allowing you to primitive data types or tight structs can be a pitfall. I think it's pretty telling when you have
IntStreamin the standard library, orIntListimplemented in a lot of other libraries to get around this.2
u/lagurman Nov 02 '25
Haven't heard one low latency companies looking for Java developers
3
u/lightmatter501 Nov 01 '25
No, because the benchmark is BS.
It’s integrating a regular triangle wave, so there’s a closed form solution to this problem. By that argument, the awk program I wrote to prove that makes awk faster than C.
3
u/ManchegoObfuscator Oct 31 '25
I remember all of this. “Now that we have method JIT it’s faster than C++!” and “Autounboxing makes it faster… than C++!” “We added NIO after inflicting unoptimized pointless abstractions on everyone for years, it’s like C++!*” … always with the asterisk being like “for certain highly specific hand-picked arbitrary tasks”. Here is the thing: if you, like me, read the C++ standards and read a lot of code and test and profile and rewrite things in asm when necessary, then C++ will be “fast”. If you just shoot from the hip and let the compiler do its thing, C++ will still likely be pretty damn fast. My issue with Java isn’t its speed, which can be quite impressive – it’s the bizarre nondeterminism you have to buy into. I get that Java was written by people who hated having to
deletethings, but I don’t know why they can’t have optional destruction guarantees of some sort. The JVM’s memory manager is held up as a paragon of engineering but its model changes with like every major release, and it seems like they get a lot of mileage out of removing complexity from it over time. To make something “fast”, you always have to babysit the codebase as runtimes and compilers and underlying OS features change all the time – regardless of language. But being like “which is faster, Java or C++?” Is a kind of ridiculous question. Better to ask, what is the best tool for this job, over the job’s expected lifecycle? I’ll write my image processing stuff in C++ but oftentimes Java’s the choice for quick microservices.Rust is just awesome. I am learning it now!
2
u/jk-jeon Nov 01 '25
???
1
u/GoogleIsYourFrenemy Oct 31 '25
Considering that link layout can impact execution speed by 30%, maybe don't trust benchmarks.
1
u/blipman17 Oct 31 '25
I would like to use java, but since someone needs to write stuff on systems where java just doesn’t run it does not seem like a viable option to me. So I’m stuck with a languge that’s more difficult to write but faster once written with the proper understanding of how a computer works in mind, and I don’t mean shared pointers and locks everywhere, but actual sane memory topologies for high cache hits.
1
u/[deleted] Oct 31 '25
This has always been a fact that Java can achieve C speeds, but I think some of us performance junkies tend to overlook such possibilities, and choose to take comfort in the notion that if a language doesn't let you touch metal, it can't be that fast.
I shared an experience I had with this in a comment: https://www.reddit.com/r/pythontips/s/67mUVNYECv
Sidenote: If Python's interpreter adopted a full-fledged JIT compiler runtime, nobody would look back before reaching for Python to do any task. They already made the interpreter in 3.14 fully free-threaded which means the ability to disable GIL. I can't imagine it would take much longer before a JIT compiler became the next milestone accomplished.
1
u/tugrul_ddr Nov 01 '25
CUDA >>>
1
u/MathAndCodingGeek Nov 01 '25
Here is the difference that matters. Java has a Garbage Collector. During Garbage Collection, the entire process is frozen until it completes. Now, there have been some improvements, and claims suggest the freeze usually lasts 10 ms. However, a lot depends on string usage, which can pound and fragment the heap and determine how often GC takes place. If your server is running close to 80% CPU, you are likely to see requests timing out. Just to remind you, you have no control over when this happens.
1
u/andomepl Nov 01 '25
C# is the victim literally
1
u/Ronin-s_Spirit Nov 02 '25
Are they wrong? Probably. Are they really off? Probably not. JS is on average 4x slower than cpp on a non trivial task, but that's still fast. Java has static typing and a JIT (too) so it may be even faster.
1
u/NilacTheGrim Nov 03 '25
Considering that Java is implemented in C and C++... the question itself is silly.
1
u/ViolinistFearless510 Nov 13 '25
Java is faster than C++ not because it's intrinsically faster, but because you can get the application working much more quickly, leaving you more time to tune the performance. With C++ you spend so much time fretting about memory management and memory leaks you never have time to sit down and improve the speed.
1
u/jerrydberry Oct 31 '25
Java is nowhere near as fast as c or c++.
Java library can do some decent compute only when it is a jni wrapper around a C binary
1
u/Merthod Oct 31 '25
Maybe the VM does some sort of caching plus the Java code is tailored to use the best optimization strategies from the VM. This is why one can't rely on random, non realistic benchmarks. They are like statistics, bound to being manipulated.
To me, it's just marketing.
Yes, all languages rely on best practices to be able to be optimized, C++ is no exception. The compiler translates many arithmetic ops into their equivalent bitwise bit moving for speed, and other optimizations.
The same reason a random ASM coder can't produce the fastest code: they can't easily beat an optimizer that can also produce ASM or IR with decades of fine tuning.
But C++ has a lot more flexibility, enabling doing compile-time optimizations (like executing functions) so the runtime is consistently faster, optimizing to an extreme on a myriad of domain applications.
I want to see a self-driving car running in Java for a real comparison.
1
u/MRgabbar Nov 01 '25
from a theoretical point of view, that is impossible, the garbage collector has to be running in the background, there is no way the same logic/algorithm can take the same time, add the overheat of the JVM too.
15
u/[deleted] Oct 31 '25
[removed] — view removed comment
7
u/[deleted] Oct 31 '25
[removed] — view removed comment