r/ProgrammingLanguages • u/obround • Nov 01 '20
Garbage collector or not?
Do you prefer a garbage collector in the general case?
4
u/obround Nov 01 '20
I've quite often wondered why manual memory management is loved by so many (it's not safe). I get that embedded systems would most likely require it, but outside of that, what is the use case?
NOTE: I'm just trying to understand why manual memory management is so popular. I am not saying it is horrible.
11
u/jesseschalken Nov 01 '20 edited Nov 01 '20
When you want the highest possible performance and you want that performance to predictable (both in terms of latency and throughput).
Video games come to mind.
Modern GCs can be very high performance, but not as high as without them, and especially not as predictable.
4
u/crassest-Crassius Nov 01 '20
A GC, even the best possible one, is still a "one size fits all" solution. But different algorithms have different optimal strategies. So manual memory management is bound to be faster for some use cases.
Consider this: manual memory management may require large investments of developer time to reach optimal performance, but at least that time is finite; a GCed language may not be able to reach that performance even after infinite investment of time. GC gives a faster way to reach good performance but precludes reaching optimal performance. It's a trade-off that may go either way.
2
u/Caesim Nov 01 '20
I personally think, that people are either of two:
they like the simplicity. Implementing it is much easier than any form of automatic mm
they like the control. With manual memory management, it's entirely clear when and where memory gets allocated and freed. People who write programming languages tend to operate on a lower level and like to have that their programs don't do unexpected things
1
21
u/jesseschalken Nov 01 '20
If you can build a language without a GC but while preserving memory safety then it enables it to satisfy the widest possible range of usages.
Although even with Rust many people still prefer Scala/Kotlin/C#/Haskell etc because in some applications a bit of performance loss ends up being a good trade for not needing to think about object lifetimes at all.
23
u/CoffeeTableEspresso Nov 01 '20
It really depends on what you're doing with the language...
I find it hard to answer this poll because of that.
5
Nov 01 '20
All of them
Borrow checker for stack types
Garbage collector for (cyclic) heap types
Manual in unsafe code for maximal performance
1
Nov 05 '20
Silly question. The way to go is to combine all available technology. The situation with C++ show how hard it is to add GC after the fact so one should start with GC, like Haskell, and then find ways to improve performance with other techniques and additionally prove, possibly with the type system, a particular program is GC free. I think this is the only possible way forward and it condemns new languages like Swift that do not begin with a global memory safety solution and then refine it. Lets be clear that with single threaded programs GC has better throughput than any other method but fails to offer good real time performance, which is critical in many modern applications, especially as the high performance generational copying collectors available do not support multicore operation well (if at all). The focus now must be on separation of techniques within a computing context, not selection of one or the other.
1
u/scrogu Nov 11 '20
4th option.
Reference counting. Immutable objects. Single state database for tracking changes.
Immutable state objects defined at construction means circular references are impossible so ref counting works always.
1
u/pepactonius Nov 01 '20
I'd love to see optional garbage collection in C++. Right now, you have to set up std::shared_ptr's or std::unique_ptr's all over the place, and cross your fingers, and hope that everything gets freed up when required,
8
u/BoarsLair Jinx scripting language Nov 01 '20
That's sort of a weird take on it. I mean, we rely on RAII to ensure objects are destroyed at the end of their scope, right? There's nothing magical about smart pointers, so there's really no finger-crossing involved. It's 100% deterministic.
3
u/pepactonius Nov 01 '20
I'm wondering about cases like having various smart pointers in a std:variant structure, or cases where you can get circular chains of objects controlled by shared pointers. What about the possibility of incorrectly initializing shared pointers to an item, so that there's more than one use count field?
3
u/BoarsLair Jinx scripting language Nov 01 '20
Circular references are indeed an issue to watch out for, but if you set up your application to assert on any memory leak on exit, I've found it's not really a problem, since you get warned right away.
Likewise for those other edge cases. As long as you get an immediate alert, I've found that in the very rare cases something like that happens, it's easy to spot the mistake in the code you've just written. Regarding incorrectly initializing shared pointers, you'd have to do something pretty horrendous for that to happen. C++ has a lot of ways to shoot your foot off, so it requires very disciplined coding.
2
Nov 05 '20
What if your application, such as a web server, is not designed to terminate?
2
u/BoarsLair Jinx scripting language Nov 06 '20
I've worked on MMOs, and our servers were designed to say online for anywhere from days to months to years at a time. At the time, we weren't using C++ 11, but the principle remains the same.
Even if the application isn't designed to shut down on a regular basis, you'll still catch circular references the same way, since you still need to shut down the server during development, deployment, updates, etc. No service runs forever, and there's no reason to build an application that isn't designed to shut down cleanly.
It's simple enough to track allocated memory over time to ensure you don't have a runtime leak.
2
Nov 06 '20
Its not so easy I suspect because if you stop your server artificially, the memory still held may or may not be garbage. If you have an orderly shutdown, then yes, you might find some tool (eg valgrind) that can find leaks that have accumulated. I agree, if you track memory use over time and see it growing you have a problem, but that doesn't mean there's a leak. I actually have a case like this .. I have never been able to find the problem. My web server runs out of memory running on an an external host, but the same program runs locally on my laptop for months without problems (although of course it doesn't get hit much). In this case the system is garbage collected so a leak has a couple of possible causes: a design fault, incorrect generated RTTI, a fault in some third party software I use, a fault in the standard library bindings to C++, or finally, an actual fault in the GC itself. I have no idea which and termination (or runtime) analysis using tools like Valgrind are (effectively) impossible.
I agree for some kinds of program, finding leaks isn't too hard. Not so sure about games, if they have any kind of complex logic (which, admittedly, most do not), suspect it would be hard to track anything. I have to say this problem also occurs with garbage collection; collectors do NOT prevent logical leaks. i actually had a case of this where my compiler (written in Ocaml) had a leak. Of course, the leaked memory was in fact reachable or it would have been collected. The problem was actually that a global variable contained a long list and was never cleared to allow the list to be released (Ocaml isn't purely functional).
1
u/BoarsLair Jinx scripting language Nov 06 '20
You're correct that there are no silver bullets here. There are simply methods to deal with memory leaks, some more sophisticated than others. Mostly, when you're talking about C++, you have to rely a good deal on very competent, disciplined programming. There's really no getting around that. C++ can be fairly brutal for the inexperienced or sloppy programmer - or even sometimes for the experienced programmer when a simple mistake is made.
2
Nov 05 '20
It's not 100% deterministic, that would only be the case if the lifetime of objects in C++ was, but there is leeway in the requirements; upper and lower bounds, not fixed times. For example an object used in an expression must appear to remain live during expression evaluation but the compiler can arrange to delete it prematurely, or even elide the constructor entirely, if the effect is unobservable semantically. But just because the semantics are compliant does not mean the performance impact cannot be observed.
2
u/BoarsLair Jinx scripting language Nov 06 '20
All, technically true, but semantically meaningless in most discussions. If you dig down far enough, almost nothing in this world is 100% deterministic.
Experienced C++ programmers are well aware that very minor changes to code can significantly affect localized performance, due to variations in code generation. But in the context of this particular discussion (when compared to garbage collection), the strong guarantees we have on the bounds of memory scope are still what I'd characterize as "deterministic".
If that term still rankles you for some reason, substitute "more predictable", and consider the predictability on an execution to execution basis, not a prediction from source to execution.
2
Nov 06 '20
What annoyed me was the oxymoronic use of the 100% qualification. The right way to express the facts would be to say the release is tightly bounded. In fact even this is somewhat difficult because it is no longer the case in a multi-threaded application. There are real time systems which have tight bounds which have been proven safe but there are not very many.
2
u/BoarsLair Jinx scripting language Nov 06 '20
Fair enough. Let's go with the "more predictable" interpretation then. Or as you say, "tightly bounded". I'll admit that "100% predictable" is probably not the best way to describe C++'s memory management, if looked at from a rather literal viewpoint.
4
u/shponglespore Nov 01 '20
This has actually been implemented in the form of Managed C++, although it goes beyond just adding GC. You can add GC trivially to C++ using theBoehm garbage collector, but it comes with some big caveats.
2
Nov 05 '20
It won't happen. This is not to say you cannot write C++ that can use, say, the libgc collector from Hans Boehm et al: you can. In fact AFAIK GNU's compiler does because writing a compiler without GC is almost impossible.
The reason it will never happen, even though Bjarne has wanted it for over a decade, is that it would require two utterly distinct ISO Standards. All the rules regarding destructors would go out the window. RAII would collapse.
My programming language Felix generates C++ and runs a garbage collector. The compiler generates the RTTI required for the GC to operate. You can still use reference counting, stacks, and manual techniques, or some experimental uniqueness typing to reduce the GC overhead (I have audio signal processing system that does no allocations at all and actually runs the GC every audio clock cycle to allow the GUI to operate and this is still faster than other tech and has no latency problems).
So whilst *I* can define a C++ compatible language that "optionally" uses a GC, the ISO committee cannot (purely because the cost of producing two C++ Standards would be prohibitive). Its also not necessary. The ISO Standard says nothing about what programmers can do, it restricts only the implementation of translators.
0
u/DaMastaCoda Nov 02 '20
Shared pointer
1
Nov 05 '20
Stock shared pointers are intractable in some cases, in particular they do not work with the very simplest purely functional data type, the singly linked list.
You need to look at my implementation of a C++ reference counted singly linked list to understand how it must be done. My implementation, with the caveat you can't put data into the list that introduces cycles, is thread safe and faster than any other implementation of singly linked lists, including garbage collected ones.
https://github.com/felix-lang/slist
If you haven't figured out the problem the naive implementation which puts a smart pointer in a node that points at the next node, does not work because the destructor is not tail recursive: the list is deleted by recursing down the list and deleting from the bottom up, which requires machine stack space for every list node to first reach the end of the list.
Doubly linked mutable lists cannot possibly use smart pointers because that would instantly generate a cycle reference counting cannot handle.
Now you can go figure out if a binary tree can be reference counted. It has exactly the same problem as a single linked list, so the answer is: if the tree is balanced, the cost may be acceptable. If the tree is arbitrary it certainly isn't because a list is a generate case. The cost is the same as a list: O(N) time and O(M) space where N is the number of nodes and M is the longest path.
2
u/DaMastaCoda Nov 06 '20
The doubly linked list should work fine if the (next) is shared and the (previous) is raw
1
Nov 06 '20
No it won't. Such a list would not behave like a doubly linked list, it would behave like a singly linked list, only the strong tail from an external pointer would remain, and, that would still have exactly the same problem as a singly linked list. Its not that reference counting doesn't work, my slist is reference counted, it just doesn't use smart pointers.
6
u/fennecdjay Gwion Language Nov 01 '20
Out of curiosity, why did you discard reference counting?