5 ms·
Classic RAII in C++ is a limited form of ref-counting (only one ref). I have to disagree with your second statement, ref-counting is extremely fast. If you con
by rian 13y ago
Classic RAII in C++ is a limited form of ref-counting (only one ref).
I have to disagree with your second statement, ref-counting is extremely fast. If you consider it a GC then it's the fastest GC. It's also deterministic and does not pause.
- pcwalton 13y ago> If you consider it a GC then it's the fastest GC. It's also deterministic and does not pause. No, it's not, not unless you use a lot of cleverness. "We find that an existing modern implementation of reference counting has an average 30% overhead compared to tracing…" (They did perform a lot of optimizations to get it up to speed with tracing garbage collection... however, these are far beyond what shared_ptr does.) http://users.cecs.anu.edu.au/~steveb/downloads/pdf/rc-ismm-2012.pdf http://users.cecs.anu.edu.au/~steveb/downloads/pdf/rc-ismm-2...
- rian 13y agoI'm a bit skeptical of the results of that paper without the seeing the source code and in what contexts they are performing the comparison. One can always find situations where one scheme is faster than the other but I'm not totally sure if micro benchmarks are representative of the real world. In long-lived servers, ref-counting can be preferable because it avoids random pauses. Maybe it's a latency vs throughput performance dichotomy. But yeah, thanks for posting that.
- danbruc 13y agoReference counting doubles the number of memory access - you have to update the reference and the counter every time. That is a big performance hit. Reference counting may randomly halt your code, too, because you never know when you hit zero and the resource gets freed.
- mcguire 13y agoAnd you don't know how many resources will be freed when you drop the last pointer to that giant tree structure. Of course, you could queue up and lazily delete the resources, but then you're back to nondeterministic behavior.
- lokedhs 13y agoTwo extra memory accesses plus whatever overhead for you have for locking if you are multi-threaded? That's pretty much the opposite of fast. With refcounting you have: - Slow memory allocations (need to manage a fragmented heap) - Slow accesses and pointer handovers (updates to the refcounter) - Slow free (need to manage the free list) - No asynchronous pauses (since there is no garbage collector) With a GC, you get: - Fast allocations (usually just an "add" instruction since the heap is not fragmented) - Zero cost accesses and pointer handovers - Zero cost free (just stop using the pointer) - Some asynchronous pauses and CPU usage while running the GC It turns out that the cost of the first three points when using refcounting are much higher than that of the GC. Another reply to your post included references to actual research on this subject.