5 ms·
This is missing something though: "new" and malloc() are just like managed memory: convenient, but sometimes (and often unpredictably) slow. Some people eschew
by jzwinck 13y ago
This is missing something though: "new" and malloc() are just like managed memory: convenient, but sometimes (and often unpredictably) slow.
Some people eschew Java and the JVM due to the spectre of garbage collection ruining their quasi-realtime system. But others embrace the JVM, organizing their programs to avoid garbage collection during critical times (which could last for hours or days).
With C and C++ it is the same, but backward: people flock to these languages for the predictable performance. Yet once there, they discover they must avoid the default allocator, for it is a source of unpredictable delays. Pooled allocators are created, and the end result is much the same as for the JVM folks.
- pkolaczk 13y agoThe funny thing is that most of STL gives no realtime guarantees either, even if you use a custom realtime allocator with it. E.g. vector.push_back takes O(n) time sometimes. Running a chain of destructors caused by reference count dropping to 0 can be unpredictable as well.
- ArbitraryLimits 13y agoI once had to re-implement the pieces of the STL I wanted in a real-time embedded system, for precisely this reason (well, that plus the fact that STL's use of allocators is broken, and I wanted to be able to allocate from fixed-size pools to avoid non-O(1) trips through an allocator at run-time).
- cma 13y agoBut you can be sure of when those "sometimes" will be with e.g. std::vector::reserve http://en.cppreference.com/w/cpp/container/vector/reserve http://en.cppreference.com/w/cpp/container/vector/reserve If you want realtime guarantees, you have a lot more unpredictable problems, like CPUs having cache.
- pkolaczk 13y agoYep, but exactly the same applies to Java. Just preallocate all your objects statically and you're never going to have GC problems :P
- cma 13y agoIf you don't want the occasional O(n) copy on growth, use an stl list with a custom allocator.
- yongjik 13y agoreserve can be very easily misused. For example, let's assume a function append_10_items_to_vector. Since we're adding 10 items, we may get a better performance if we call reserve() before 10 push_back()s. Right? Not always. If we have a loop that calls our append_10_items_to_vector N times (on the same vector), then your reserve() just transformed the loop into O(N^2) code. Without reserve, it would be O(N). As a rule of thumb, use reserve only if you are really sure that nobody's ever going to add anything more to your vector in the future.