8 ms·
A Garbage Collector for C and C++
- eatonphil 11y agoWhy would this outperform malloc for multi-threaded programs? Is that a property of GCd programs in general? Edit: That is, is it typical for GCd programs to outperform manually-memory managed programs in multi-threaded environments?
- deleted 11y ago[deleted]
- sitharus 11y agoThat all depends on how you manually manage memory. Older versions of malloc performed poorly with frequent allocations. Bohem GC allocates in large(ish) slabs, so it can manage many small objects more efficiently than OS malloc. Modern malloc replacements like jemalloc also do this for manual allocation.
- rayiner 11y agoMalloc() is easy to write in multi-threaded environments. You can just have per-thread pools of allocable memory, which is what most multi-threaded mallocs do. Free() on the other hand isn't. Among other things, what do you do when you free an object? You can return the freed memory to the local pool of the thread that does the free() operation, but that can result in pathological behavior when, e.g. one thread consistently allocates objects while another frees them. In that case, a bunch of free memory accumulates in one thread. Production multi-threaded allocs have mechanisms to rebalance these per-thread pools, but that involves synchronization overhead. If most objects die before a GC cycle, it can be faster to just stop all threads and reclaim that memory in bulk as Boehm does.
- deleted 11y ago[deleted]
- pcwalton 11y agoThat seems independent of tracing GC versus manual memory management, though, doesn't it? jemalloc/tcmalloc could stop all threads and flush pools in bulk as well if it decided that it was faster to do so. (From looking at the code, jemalloc doesn't, but it could.) More broadly, if batched deallocation is indeed faster, you can get that behavior in a manually memory-managed scenario. You aren't forced into prompt reclamation. It's just that prompt reclamation is usually faster for cache reasons and improves memory consumption, so malloc implementations take advantage of the opportunity.
- zik 11y agoFans of GC claim that GC outperforms malloc() based on some studies that were done a long time ago. The argument is that repeated malloc/frees are less efficient than a bunch of GC allocs and then a single garbage collection. The reality seems to be a bit different. In practice GC programs tend to use significantly more memory which can impact performance. And the trend towards low GC pause times costs additional CPU. Beyond that we're now using much larger multi gigabyte GC memory pools which can also lead to poor GC performance. So overall people these days see lower performance with GC systems compared to malloc.
- kasey_junk 11y agoProve it.
- jeffsco 11y agoPlease cite some evidence. As a GC fan, I'm interested in this question. (In my opinion, GC is more than worth the cost.)
- velco 11y agohttps://people.cs.umass.edu/~emery/pubs/gcvsmalloc.pdf https://people.cs.umass.edu/~emery/pubs/gcvsmalloc.pdf
- rurban 11y agoThey are only talking about slow, conservative, stop-the-world collectors there. They have to scan the full heap. You shouldn't compare apples with oranges.
- velco 11y agoI find the methodology of the research to be solid, the collectors to be representative of the different approaches in the field and the conclusions to be consistent with the gut feeling from experience: "With only three times as much memory, the collector runs on average 17% slower than explicit memory management. However, with only twice as much memory, garbage collection degrades performance by nearly 70%."
- jandrewrogers 11y agoYou can often trade space complexity for time complexity and concurrency. Garbage collectors typically require integer multiples of the memory footprint of manual memory management to offset the higher intrinsic computational cost of garbage collection algorithms. While malloc() has much less work to do, the default malloc() is often not that fast and it is possible in principle to design a garbage collector that can leverage space complexity to beat the generic malloc(). The caveat is that properly engineered C/C++ hardly ever uses malloc() or similar to manage memory. Relative performance in real systems would be between a garbage collector and one of myriad not-malloc() mechanisms typical of C/C++ that are much faster and often safer than using malloc(). If you are among that subset of programmers that uses malloc() ubiquitously, an argument might be made that a garbage collector is a better choice if you have plenty of memory. However, this argument would be about safety; if you are using malloc() ubiquitously then you obviously do not care about performance prima facie.
- kasey_junk 11y agoThis is an argument I don't understand. It is exceedingly common for performance sensitive applications in GC environments not to allocate either, because quite simply allocating/deallocating in any environment is expensive. Why in the world is it fair to compare C/C++ programs that don't allocate to Java/C# ones that do? Another way of saying this is if you are using new ubiquitously then you obviously do not care about performance prima facie. At the end of the day GC'd versus manual memory debates seem to fall into 2 axis. Complexity vs correctness and total memory available vs concurrent access to said memory. At this point in time the difference in performance between a C application and a Java one comes down to correctness and access to low level memory layout primitives, not GC vs manual memory.
- okasaki 11y ago> This is an argument I don't understand. It is exceedingly common for performance sensitive applications in GC environments not to allocate either, because quite simply allocating/deallocating in any environment is expensive. Is that possible? I thought all objects are heap allocated in Java?
- BinaryIdiot 11y agoI like that it can be used as a leak detector! I'm not sure I understand the point beyond that but then again I am in love with RAII semantics so I'm probably a bit biased here.
- vidarh 11y agoConsider it a safeguard. One one hand it can detect (some) leaks. On the other hand if/when your app leaks it can mitigate the consequences of those leaks. For some very specific types of apps it can also be sufficient to ditch traditional C/C++ memory management, and you can actually even gain speed doing so. Consider e.g. code that runs a job. Most of the time you know it will need less than 32MB (or whatever) total over the (short) lifetime of the process. So you tune the GC accordingly to not trigger any collection at all until above that level. Now most of time, a collection will never get triggered, and you're happy - all the memory is just returned to the system at the end in one swoop. But if occasionally a job requires lots more, the GC may provide sufficient cleanup to still make it viable not to include any memory management. My first large CGI-era webapp was in C++ and relied exactly on lots of hacks like deferring all memory de-allocation until exit to improve performance (and it worked very well - it had a considerable performance impact; other hacks included static linking to drastically cut the loading cost). We didn't use a GC; instead we had to take extra care when we knew we were going to make large allocations to do manual de-allocation in those cases if the request was potentially long-running. I'd have loved to use the Boehm GC for that.
- pjmlp 11y agoWalter Bright uses this trick in his D compiler. Memory is not freed, just by the OS. http://www.drdobbs.com/cpp/increasing-compiler-speed-by-over-75/240158941?queryText=Walter%2BBright http://www.drdobbs.com/cpp/increasing-compiler-speed-by-over...
- kentonv 11y agoThis has been around for a long time. The problem is, GC is not just something you can bolt on, it's a fundamental part of the language that colors everything you write -- and it fundamentally clashes with the way C++ is normally written. In particular, C++ (and Rust, etc.) stresses RAII (Resource Acquisition Is Initialization), in which you write classes with destructors that cause the object to release its resources as soon as it goes out of scope. "Resources" here often means heap memory, but can also mean a whole lot of other things (file handles, child processes, network connections, arbitrary resources on remote network services, etc.). In GC'd languages, the GC really only handles heap memory. Yes, you can sometimes rely on finalizers to free other kinds of resources, but generally you will find this doesn't work out well: most GC algorithms do not make any guarantees about how soon an unreachable object will be cleaned up, and they tend to use heuristics that assume that the cost of not cleaning up an object is exactly whatever RAM it is using, nothing more. Often, if your process is not allocating any new objects, the GC will never run at all. Thus in GC'd languages you often see classes with methods like `.close()` or `.dispose()` for eagerly releasing non-local resources. These resources have to be managed manually, just like heap has to be managed in non-GC languages. The beauty of RAII is that you can use it to manage any kind of resource, but GC languages don't typically support RAII because it does not mix well with GC semantics. These differences completely change how APIs in these languages are designed. Essentially, adding GC to a language -- or removing it -- gives you a different language that happens to share some syntax, and probably not a very good language since all that syntax was designed around a fundamental assumption that no longer holds. I kind of wonder if a preference for GC languages is in part responsible for the way distributed systems are typically designed these days -- namely, the emphasis on stateless servers, which avoids the need to do remote resource management (which is hard without RAII), at the expense of requiring a lot more machinery to make performant (e.g. complicated caching layers because all state changes have to hit storage which is sllloowwwwwww).
- pjmlp 11y ago> The problem is, GC is not just something you can bolt on, it's a fundamental part of the language that colors everything you write -- and it fundamentally clashes with the way C++ is normally written. C++ and C yes, because these are systems languages where everything goes, which make impossible to apply certain classes of GC algorithms. Apple's failure to make one work in Objective-C is proof of that. However there were systems programming languages with GC, like Cedar, Oberon and Modula-3. Just like C++, with value by default, stack allocation and since they are safe by default, requiring explicit unsafe blocks, their GCs were better than anything C or C++ can ever get. Still, ANSI C++11 did get a GC pluggable API. > these resources have to be managed manually, just like heap has to be managed in non-GC languages. Only if the programmers are too lazy to learn how to make use of using/try-resource/defer/scope, or higher order functions. But GC critics always fail to acknowledge these language features.
- lisper 11y agoA Lisp that uses the Boehm GC: https://github.com/rongarret/Ciel https://github.com/rongarret/Ciel
- BruceM 11y agoCLASP (https://github.com/drmeister/clasp https://github.com/drmeister/clasp), a Common Lisp, can optionally use one of Boehm or the Memory Pool System (http://www.ravenbrook.com/project/mps http://www.ravenbrook.com/project/mps). Open Dylan (http://opendylan.org/ http://opendylan.org/), a Lisp-like language without Lisp-like syntax, also can use Boehm or the Memory Pool System.
- abalone 11y agoWould it be conceivable to implement Automatic Reference Counting for C/C++? Basically gets you the advantages of GC without the performance impact of GC cycles, because it does all its magic at compile time. On a related note I'm excited about Apple open sourcing and porting Swift to Linux with an eye towards server-side code, specifically because of ARC. Garbage collection has been a concern for web services in particular when it comes to 99th percentile latency. Things run fine and then boom, GC runs, slowing down a few unlucky requests. ARC just makes memory-management performance deterministic, no tuning needed.
- andrewchambers 11y agoDon't you know about the std:: smart pointers?
- antimagic 11y agoARC actually has some interesting advantages over smart pointers. For one, there is a large amount of static analysis done at compile time that allows the system to avoid unnecessary increment/decrements of the reference counter - this can have significant performance improvements in tight inner loops, and can't be achieved using smart pointers.
- plorkyeran 11y agoMy experience has been that the awesomeness of ARC's optimizations is greatly overstated. The compiler inserts retain/release pairs around every operation that could potentially need them, and then the optimizer eliminates the redundant ones. Pretty much the only interesting nonlocal optimization it does it turn autoreleased return values into retained returns, which isn't an issue for shared_ptr to begin with.
- pjmlp 11y agoNothing in ANSI C++ forbids compiler vendors to make their compilers *_ptr<>() aware, but AFAIK none of them take advantage of it.
- 11y ago
- denim_chicken 11y agoI feel that this library is a testament to the power of C and C++ (and their ecosystem).