3 ms·
Java new operator leaves C++ new operator biting the dust. But then you allocate C++ objects in the stack, and that's a couple of orders of magnitude faster.
by Shorel 5y ago
Java new operator leaves C++ new operator biting the dust.
But then you allocate C++ objects in the stack, and that's a couple of orders of magnitude faster.
It really comes down to if you can use the stack, or you have to use the heap.
- snovv_crash 5y agoIn C++ with a thread-local allocator or a memory pool you can effectively skip the global allocator (or at least amortize it to 0). C++ gives you the tools to fix these kinds of bottlenecks if you need to, even if it is added complexity.
- moonchild 5y agoYes, and you can similarly preallocate memory in java (though you will be unable to do type punning). Java gets used in high-frequency trading which has very tight latency and overall performance requirements, to great effect.
- snovv_crash 5y agoWriting a pool in Java doesn't necessarily give you memory locality guarantees though, making you much more sensitive to cache:data size ratios. In Java you end up rewriting your algorithms as AoS instead of SoA just so that you can work with cache-aware layouts of primitives.
- nonameiguess 5y agoThis is because the JVM preallocates a bunch of memory to manage its own heap and doesn't need to make a system call and suffer a userspace/kernel space context switch every time you use the new operator. Plenty of C++ memory pool libraries will do exactly the same thing for you; it's just not built into the language runtime itself, as you don't necessarily need it if you aren't going to be doing heap allocations at all. In Java, you really have no choice unless you're writing some extremely simple toy program that only uses primitive types, at which point why are you bothering to use Java?