- case 1 (standard java): you allocate heap memory. After you finish with it you wait for the java GC to clean it up.
- case 2 (low latency java): you allocate heap memory but disable java GC. Either you hold on to all your objects, or you leave unreachable garbage orbiting the earth forever.
- case 3 (c++): you allocate heap memory with the expectation of releasing it, so the compiler sets up housekeeping in advance for the anticipated delete(). This housekeeping overhead is somehow similar to try/catch before c++11 ‘noexcept’.
Stroustrup suggested that #2 will be faster than #3, but #3 is faster than #1. I said “But c++ can emulate the allocation as jvm does?” Stroustrup said C++ is not designed for that. I think he meant impractical/invalid. I have seen online posts about this “emulation” but I would trust Stroustrup more.
- case 4 (C): C/c++ can sometimes use local variables to beat heap allocation. C programmers use rather few heap allocations, in my experience.
Note jvm or malloc are all userland allocators, not part of kernel and usually not using system calls. You can substitute your own malloc.
— https://stackoverflow.com/questions/18268151/java-collections-faster-than-c-containers top answer by Kanze is consistent with what Stroustrup told me.
- zero dynamic allocation (Similar to Case 4) is always faster than even the fastest dynamic allocation.
- jvm allocation (without the GC clean-up) can be 10 times faster than c++ allocation. Similar to Case 2^3
- Q: Is there a free list in JVM allocator? Yes
- c++ Custom allocators managing a pool of fixed-sized objects can beat jvm
- jvm allocation often requires little more than one pointer addition, which is certainly faster than typical C heap allocation algorithms in malloc