55 points · by criddell · 10y ago · 92 comments
Why can't you acknowledge that there are problems that have GC as the only and best solution?
(Note: it's possible to mix memory management approaches, e.g only pointers to graph nodes are being garbage collected and everything else has a nice hierarchical ownership.)
>Why can't you acknowledge that there are problems that have GC as the only and best solution?
Your prelude and the followup question is not well-formed.
C++ programmers do not have a bias against GC as a specific problem-solving technique. In fact, expert C++ programmers can embrace GC so much that they can write an entire virtual machine[1] with GC and a DSL[2] for that vm that takes advantage of memory safety. Both the CLR vm and the (original) C# compiler were written by C++ programmers.
What the C++ community doesn't want is GC in the C++ base language itself or the standard runtime. That's a very different concept from a generalized "C++ bias against GC".
In other words, the following is unacceptable:
std::string x = "Hello, " + fullname; // cpu cycles spent on GC
Those cpu cycles spent on constantly checking if "x" is no longer reachable is cpu power that's taken away from rendering frames of a 60fps game, or computing numeric equations or high speed quantitative trading. C++ programmers don't want GC as a global runtime that you can't opt out of. Also, global GC often requires 2x-3x the memory footprint of working memory which is extremely wasteful for the resource constrained domains that C++ is often used in.Herb Sutter's presentation is compatible with "pseudo-GC-when-you-need-it" without adding GC to the entire C++ standard runtime.
[1]https://en.wikipedia.org/wiki/Common_Language_Runtime
[2]https://en.wikipedia.org/wiki/C_Sharp_(programming_language)
> std::string x = "Hello, " + fullname; // cpu cycles spent on GC
you are already spending cycles on memory management (if C++ allocates character data on the heap which I think it does). You are searching for free space in the heap, possibly synchronising to do that, and so on.
With a GC you may even use less cycles here! For example a copying GC could mean that you can allocate with a simple thread local bump pointer.
So in your statement you are already paying an unknown cycle cost for memory management. Why do you care if it's GC?
Your answer is probably the variance in the number of cycles - the noticeable pauses - which is a reasonable concern.
This is one of the bigger reasons people use C++ and even techniques within it to explicitly collect such items at a known point in time. (Techniques such as marking items as dead in an array but still keeping them in there until the end of frame, etc)
This is equally true for explicit memory allocation. The point is that on some allocations under GC, it will have to collect garbage. And collecting garbage will tend to be more expensive than explicit frees, because it usually has to do work to discover what is garbage.
For example, in C every time a `const char *` appears in an API there has to be an implicit contract about who owns the string and how to free it. A language like Rust improves on this by enforcing such contracts, but the contracts still complicate every interface.
In a GC'd language you can just forget about these issues and just treat strings (and other immutable objects) almost as if they were ordinary fixed-sized values.
Put very simply: do your choice for your problem and deal with its consequences.
Memory fragmentation in manual memory management often comes at a similar or higher cost, which is often "forgotten" and neglected, because it is hidden:
https://bugzilla.mozilla.org/show_bug.cgi?id=666058#c31
And fragmentation may grow over time much more than the typical GC overhead. Then you have to do a "forced GC" that is restarting the application. Often happens to my phone or browser. I'm not sure if it is more due to fragmentation or more due too plain old memory leaks.
Thank you for your feedback, I appreciate it.
> C++ programmers do not have a bias against GC as a specific problem-solving technique. Expert C++ programmers can embrace GC
Please watch this portion of the video, and the way the speaker is pronouncing the word "collect":
https://www.youtube.com/watch?v=JfmTagWcqoE#t=1h5m25s
Regarding general-purpose GC:
I don't support using GC for everything. If there is a problem that can only be solved with GC, it doesn't mean that we should express our entire running programs in terms of dynamic cyclic graphs. I believe we can do much better, with much fewer resources.
Herb was deliberately using circumlocution to avoid the phrase "garbage collection" so as to not poison the well. The latter part of the video explains his reasoning for presenting it that way:
https://www.youtube.com/watch?v=JfmTagWcqoE&t=1h32m55s
>I don't support using GC for everything. [...] I believe we can do much better, with much fewer resources.
This is a statement that sounds reasonable and balanced . How can anyone possibly disagree with it?!? The issue is that it's very difficult to take that universal wisdom and construct a real programming language that satisfies all the following properties seamlessly and elegantly:
1) language that has optional GC
2) has zero cost when not using it. This means no active tracing loop that checks object graphs and no large memory blocks reserved to allow reallocation and defragmention.
3) transparent syntax that's equally elegant for manual memory or GC in the same language
To make your GC-when-appropriate advice real, one has to show a real implementation. E.g. one can fork the GCC or LLVM compilers and add GC to it. Or fork the Java OpenJDK compiler and show how syntax can remove the GC on demand. Or construct a new language from scratch. There may be some lessons learned from the D Language backing away from GC. Also, Apple Objective-C retreated from GC as well.
There are indeed cases where you have to use GC on some part of your program (as you say, some graph with cycles). However, such things are still only a small part of a program, and most of your memory allocations can still be handled without a GC.
No program language I am aware of (and I don't claim to know all) are good at saying "GC this 5%, I'll explicitly handle everything else". In C++ the "GC" bit is painful, in most other languages the "I'll do everything else" bit is painful.
Of course, there is an argument that just GCing everything is as efficient as bothering with manual memory management, so why bother at all? I'm still to be convinced about that, particularly because GC systems tend to want to use quite a bit more memory, so they have room to breathe.
I haven't used rust in production, but I think it allows you to do precisely this, using the following crate: https://github.com/Manishearth/rust-gc.
> Of course, there is an argument that just GCing everything is as efficient as bothering with manual memory management
I specifically said that it should be possible to mix GC with other types of memory management.
The problem is that I often hear from C++ crowd "GC is bad, mmkay!", without mentioning that there are specific cases where you have to use/implement GC.
VAR
stackOrGlobalMem: RECORD ... END;
heapGC : REF RECORD ... END;
somewhereManual : UNTRACED REF TO RECORD ... END;
rawMem : ADDRESS;
Also valid for any other data type in the language.So one can take advantage of GC productivity, while making use of C++ like features for manual allocation when required.
I remember reading a paper with a generics module for using smart references as well.
There are other not so well know GC enabled system programming languages with similar feature sets.
EDIT: like was missing
GC is traditionally bundled into a language runtime in a way that imposes global costs, and cannot be opted out of. The GC interrupts your program in a way you have no direct control over and scans the global heap of all objects you have ever created.
C++'s philosophy is zero-cost, opt-in abstractions. So naturally anything that you can't opt out of is going to rub C++ programmers the wrong way.
Implementing GC within the language, in a way that is entirely opt-in, is fine. Any muttering under the breath when discussing this is, IMO, just acknowledging that most of our experiences are of "bad" GC, to the point that we almost don't want to use the same word when referring to "good" GC.
It's a nice philosophy, but unfortunately C++ itself often fails to deliver unless the programmer is an absolute expert on the underlying semantics. E.g. forget to pass a vector by reference or as a pointer, and you get a complete O(n) copy underneath. With other data structures, one can implement efficient copy constructors to make this pretty cheap. When an abstraction leaks details of the underlying implementation that then lead to huge non-obvious costs, that is not an abstraction.
Another example is that C++ heap allocation relies on an underlying allocator, which has overhead in managed chunks of memory, size classes, etc. The underlying allocator's alloc() and free() operations are not constant time. In fact, they are almost always outperformed by the allocation performance of GC'd languages, where bump-pointer allocation and generational collection make these overheads very, very cheap.
C++ lets you use a bump allocator if you want. malloc()/free() are just functions that you don't pay for unless you call them. That is the point! And as others have pointed out, many common data structures let you swap out the calls to malloc()/free() for something else if you want to.
As they say, C++ gives you enough rope to hang yourself. It's pretty unapologetic about not being a language meant for everyone. But, sometimes, one needs to drop down to a lower level language to boost performance. I like to apply the Pareto Principle: 80% in a higher level language, and 20% in a language like C or C++.
So I'm sticking with out params for now.
Well, it's a bit of a selection bias on your part IMO. The people who use C++ have seen the benefits of Java, python, C# and all the rest. And many of them(us) use Java, python, C# and stuff for meta-productivity build tools and the like. GC is great for some enormous set of problem domains. But for problems that cannot endure high or unstable latencies, GC is a bad solution. I'm writing C++ because it hits a sweet spot in the intersection of (low/deterministic latency + ubiquity among developers).
> Why can't you acknowledge that there are problems that have GC as the only and best solution?
There are, but I probably wouldn't have used C++ for them. In some rare cases I would but only because of momentum on an existing legacy solution.
I love LISP and Smalltalk, but I'll never ship a product in those languages. I've written a ton of C# and Java and somewhat less Javascript; those environments are fine (though I found myself paying much closer attention to object lifetime than I wanted).
I'm dead set against garbage collecting C++ because the semantics just don't fit well with the available runtimes. A few times I've written garbage collected heaps for specific types of objects; crossing the boundary between the hand-allocation world of C++ and the dynamic world of a GC environment is not a happy or particularly efficient experience, especially in the presence of threads.
A good example is Modula-3, a systems programing language that while it does have GC by default, also allows for global and stack allocation, value types, bit and structure packing and if really necessary naked pointers (only allowed in unsafe modules).
Or Mesa/Cedar at Xerox PARC with its mix of RC/GC, which is basically the same as C++ _ptr<>() + deferred_ptr<>() just implemented at the language level.
Same applies to RAII, yes it was a very good invention in C++, but many other languages do offer good ways of doing resource management, for example bracket in Haskell or withResource in others.
So re-implementing your own GC algorithm in the special case where you need it is seen as acceptable. That deffered pointer could be part of the standard library as long as those who don't need to use it don't pay any performance overhead
A not well known fact is that even the linux kernel as a GC implementation, used to collect file descriptors, but any suggestion to GCing all memory in the linux kernel wouldn't be well received.
It is true there are specific problems (e.g git repos) where you want a mutable graph over the long term -- but I have never actually had to deal with those cases, unless it was a special case with a obvious solution (like a doubly-linked list or tree).
[1] unless you cheat...
To say it another way: what we (C++ programmers, stereotypically) don't like about GC is that it incurs long search costs at unpredictable intervals. That long search cost is not dissimilar in nature (i.e. in algorithm) to the cost of this search. So it's not clear to me that the performance characteristics of `internal_ptr` would be much different from those of GC. I'd like to see the performance characteristics of the solution filled out with more detail.
And that's great! Automatic reference counting is my single favourite thing about Obj-C. Once you get the hang of using weak refs for parent objects, ARC is very easy to use, with consistent speed, low memory usage, and immediate deallocation of dead objects.
I'd go as far as to say that Objective-C is a big reason why iOS has historically been faster and smoother than Android. It's not the world's fastest language, but there are no big GC pauses and it doesn't waste a lot of memory.
So I bet this is a good memory management style for C++ too.
The cppcon YouTube channel is full of videos that will take up my evenings, to my wife's disgust (doubt she wants to watch Bjarne talk).
The article talks duly about the data structure in question and is perfectly interesting. What it doesn't address is when this data structure comes up in practice and whether it can be handled in different ways.
In many cases, it might be desirable to search for alternative memory representations, since this data structure obviously complicates things considerably (for C++).
For example, a graph is isomorphic to a sparse array, which could avoid embedding bidirectional pointers directly into the graph nodes.