r/cpp • • 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

192 comments sorted by

View all 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.

80

u/CalebGT Oct 31 '25

And no, the performance of Java was never and never will be comparable to C++ except for applications where performance does not matter. Different tools for different jobs with different advantages.

61

u/pemb Nov 01 '25

Java has JIT compilation and can do stuff like dynamic profile-guided optimization, inlining, and devirtualization. So some Java can actually perform better than C++ in specific circumstances, especially in applications that ship one binary and can't be tuned for the specific machine and workload they're running.

The real Achilles' heel is Java's whole approach to memory, especially when the GC hits.

48

u/CalebGT Nov 01 '25

It is possible to do Java well and even easier to write C++ poorly. Good C++ code has a performance edge on best case Java. For most applications and on current hardware, it's usually not noticeable. There are pitfalls in C++ that are avoidable but easy to be oblivious to. You have to really know what you are doing to minimize how many allocations, reallocations, and copies your C++ performs for example. There are performance hits that get abstracted away inside classes. Memory management is manual, and that can be done well or poorly.

But if I am writing something with real time demands and heavy processing, I'm looking at C++. If I need to write something portable that isn't CPU intensive, I'm looking at python. If performance isn't a big concern, it might as well be super easy to implement quickly. Time is money. I have barely touched Java since college, but that's in large part because the nature of my work didn't need both portability and performance. Different tools for different jobs. Tradeoffs, not superiority across the board.

7

u/Infamous_Campaign687 Nov 01 '25

I recently had someone do a conversion of a Java Library into C++, and the first attempt was ridiculously slow. Turns out that this usually very competent developer had forgotten to reserve memory for the std::vector that replaced the Java ArrayList. So memory was reallocated many times when filling the vector. This in an algorithm that was run several times per second.

This sort of thing is handled for you in Java but will cost you in C++.

This one was far too obvious to go unnoticed because it led to a 200x time increase, but smaller ones could easily slip under the radar until you profile and see that 90% of your time is in memory allocation.

7

u/ts826848 Nov 01 '25

This sort of thing is handled for you in Java

I'm not sure about that? The main difference I'm aware of is that ArrayList's default constructor initializes with a capacity of 10 vs. std::vector's unspecified (but usually 0 IIRC?) capacity. Otherwise my impression is that they would both behave quite similarly when elements are added. They even have analogous API surfaces for this kind of thing:

  • std::vector(size_t) and ArrayList(int) for creating a new instance with a given capacity

  • std::vector::reserve(size_t) and ArrayList.ensureCapacity(int) for allocating memory for the given number of elements up front

Maybe the JIT learned to insert calls to ensureCapacity() up front, but that feels like a really brittle optimization at best, assuming it's worth implementing in the first place.

3

u/eXl5eQ Nov 01 '25 edited Nov 01 '25

Maybe because

  1. Java heap allocator is A LOT faster.

  2. No deallocation overhead. The garbage collector well handle that in background, as long as you have enough RAM. Java programs can easily consume 10x or 100x more memory than a C++ one.

  3. Array copy is always a simple memcpy in Java. No constructor overhead.

  4. No destructor overhead.

ensureCapacity() is a very high-level operation. I don't think JIT will mess with that.

3

u/eXl5eQ Nov 01 '25

Also if it's a std:vector<VeryLargeObject> vs ArrayList<ReferenceToVeryLargeObject>, that makes huge difference too.

3

u/CalebGT Nov 01 '25

Garbage collection is a convenience, not a performance gain. What processor do you think is running background routines? Holding up Java's fatal flaw as if it's a source of superiority is a special kind of cope. And regarding point 3, often in C++ it's a move instead of a copy, dramatically faster than a large memcpy. You are on a C++ sub and clearly out of your depth. Sit down.

4

u/srdoe Nov 02 '25 edited Nov 02 '25

The poster above is correct, and you should save your condescension for when you're not wrong.

Garbage collection is not simply a convenience, it can also be a performance gain. This was shown as early as 20 years ago, and the state of the art for GCs has come a long way since then.

The reasons to do manual memory management if you have a garbage collector available are not because it's more efficient overall, it's because some GCs can have unpredictable pause times, and because GCs can require more memory than manual management would.

In exchange for those drawbacks, you get:

  • Faster allocations. Java threads allocate from thread-local buffers, turning most allocations into a simple increment of a thread-local integer.

  • Faster deallocations (on average, but with the potential for those unpredictable pauses I mentioned). GCs tend to clean up garbage entire memory regions at a time, rather than freeing individual objects allocated by the application.

  • The ability to offload garbage handling to non-application threads. This is beneficial unless your program is already loading all cores constantly, because it means garbage handling doesn't slow down the application like it would in C++.

  • The ability to trade excess memory on the computer for saving CPU cycles. A C++ program doing manual memory management has to always pay for freeing memory to the allocator. A Java program using GC only has to pay anything when the GC actually runs, which it will do more rarely the more memory the host has. Since the work GCs do is mainly moving live objects around (unlike C++ where the work is mainly dealing with dead objects), running the GC less often can even mean that objects have had more time to become garbage, which can make the collection cheaper overall.

If manual memory management was actually faster, and all GCs solved was convenience, Java and other languages that want to automate memory management could have just implemented smart pointers under the hood, it would look the same to the programmer.

edit: Actually the theory behind GCs being faster than manual management for deallocation if given sufficient memory is even older than the 20 year old paper I cited. Here's a paper from 1987 describing the reasoning for why GCs can be faster at clearing garbage than manual management can.

This paper shows that, with enough memory on the computer, it is more expensive to explicitly free a cell than it is to leave it for the garbage collector — even if the cost of freeing a cell is only a single machine instruction.

2

u/DuranteA Nov 03 '25

Faster allocations. Java threads allocate from thread-local buffers, turning most allocations into a simple increment of a thread-local integer.

I am curious why you point to this as an advantage specific to GC when all high-performance general C++ memory allocators I know of already do serve small allocations from thread-local pools.

→ More replies (0)

2

u/coderemover Nov 02 '25

The theory you cite no longer holds. The gap between cpu speed and memory latency got far too big. Tracing GC thrash cache like crazy.

→ More replies (0)

1

u/CalebGT Nov 02 '25

GC is a one size fits all solution. It's fine for many applications, and can be better in many people's hands. With careful design, C++ can do better. We have to be aware of a lot of hidden pitfalls (eg std::string can be the devil if used poorly in a loop), but we can get very good at this. The really experienced guys that are doing things with really tight timing in C++ know to preallocate pools of resources for the lifetime of the process and manage them separate from allocators and also make good use of the stack. We don't all use short-lived smart pointers. I don't want a nanny that I have no control over. I don't like not knowing when she might show up and take over. Personal preference.

→ More replies (0)

1

u/ts826848 Nov 01 '25

None of those really sound like "handled for you" to me; they more sound like things which may make it harder to notice appends-without-reserving but wouldn't prevent it from showing up in general (i.e., those may reduce the smaller factors on a O(n2) operation, but they won't turn O(n2) into O(n)). Maybe I'm interpreting the phrase differently than intended, but I don't think my reading is that crazy.

1

u/eXl5eQ Nov 02 '25

If you're aiming zero extra cost, then you're right. But many people include me would be satisfied as long as it doesn't slow down the whole program significantly.

1

u/coderemover Nov 02 '25 edited Nov 02 '25

Java heap allocator is not a lot faster. It is at best order 2x faster, and often slower if you count in all the work that GC needs to do to cleanup. There is also a problem that the memory you’re getting from allocation is usually not in the cpu cache, because it’s the memory freed in the previous cycle of GC, so it’s long gone from the cache. Malloc maybe spends a bit more cpu on finding the free chunk but the chunk is usually hot. Because of the general negative effects of tracing GC on caching, the cost of heap allocation is hard to measure - it gets spread over many other lines of code and is misattributed to some other code.

1

u/eXl5eQ Nov 02 '25

Are you sure??? A normal malloc implementation would cost at least 20~30 CPU cycles on fast path, while Java bump allocator cost only 2~3 cycles. It's 10x faster!

The memory you a Java allocator returns is very likely have been prefetched into cache because Java always allocate continuous memory span, unlike malloc which has memory fragment issue.

The last official Java GC which would actually "free" dead objects is CMS GC, which had been replaced by G1 GC in Java 8, like 10 years ago. Newer GCs are all moving GC. Moving means they don't "free" dead objects, they just "move" live objects to another page, thus effectively eliminates the memory fragmentation problem.

Instead of talking based on your biased assumptions, would you please at least read some basic introduction about how modern Java GC actually works?

1

u/coderemover Nov 02 '25 edited Nov 02 '25

Instead of theoretizing, make a loop with malloc/free and compare with a loop doing new in Java and then forgetting the reference. Java will not be 10x faster. Last time I checked it was 2x faster, and that is the most optimistic case for Java, because the object dies immediately. If the object survives the first collection, which is not unusual in real programs, the cost goes through the roof. The amortized cost of Java heap allocation is much bigger than 2-3 cpu cycles.

In the great computer benchmark game there was one benchmark - binary trees - which heavily stressed heap allocation and that was one of very few benchmarks where Java indeed had a small edge - it slightly won with some of the most naive C implementations which were not using arenas. But it was very, very far from winning by 10x. Obviously it lost dramatically to the good implementations utilizing arenas.

And I know how modern Java collectors work, I’ve been optimizing high performance Java programs for living. One of the most effective performance optimizations that still works is reducing heap allocations. If they were only 3 cycles, no one would ever notice them.

Here is a good read explaining why it’s not so simple as bumping up the pointer and how the real cost is way larger than that: https://arxiv.org/abs/2112.07880

→ More replies (0)