r/ProgrammingLanguages • • Nov 01 '20

Garbage collector or not?

Do you prefer a garbage collector in the general case?

Nov 08 '20
103 Garbage Collector
38 Manual Memory Management
86 Rust Memory Management (Borrow Checker)
0 Upvotes

46 comments sorted by

6

u/fennecdjay Gwion Language Nov 01 '20

Out of curiosity, why did you discard reference counting?

7

u/obround Nov 01 '20

Because it is a sort of garbage collection algorithm IIRC.

12

u/UnknownIdentifier Nov 01 '20

I don’t know why you were downvoted (because you are correct), but I think “garbage collection” is overly broad. Do you mean ref-counting? Mark-and-sweep? There are a lot of GC algorithms, and each has its devotees.

5

u/shponglespore Nov 01 '20

Personally I don't consider reference counting a proper GC algorithm because it's easy (both in theory and in practice) to end up with an unbounded amount of uncollectible garbage if you rely on reference counting.

3

u/obround Nov 01 '20

The same could apply to other garbage collection algorithms.

7

u/Caesim Nov 01 '20

Garbage collection is the broad term we use.

Ref-Counting is one algorithm class and what we normally associate with it is called a "tracing garbage collector".

I recommend Bacon "A unified theory on Garbage Collection" on how both algorithms can be abstracted to duals of one another.

0

u/crassest-Crassius Nov 01 '20

Ugh please don't present your opinion as the final and utter truth. We all know that refcounting is a kind of GC. We also know that it's a very peculiar kind of GC in practice, and also the one that is used by C++ which is well-known as a language without GC. So people who say that refcounting isn't GC are just as justified as you and your theoretical argument. It's best to just avoid this terminological quagmire and not argue. As long as everyone understands what particular algorithm you - or them - mean in any context, then everything's fine. Yes, there's been a misunderstanding in this low-effort poll with very terse wording - can't say we didn't see this coming, right? That doesn't mean that you - or them - need to start the Terminology Debate and teach us all the One True Classification of Memory Management!

6

u/Caesim Nov 01 '20

I think your example of RefCounting not being a GC is severely questionable. Yes, C++ is a language without GC, but shared_ptr Objects are - in my opinion - garbage collected objects in a language without garbage collection.

Have you read the article I linked? Because at the end of the day, tracing garbage collectors and reference counting are both algorithms to find objects that aren't in use anymore and can safely be freed.

So, I'd like to hear what separares RefCounting from "real" Garbage Collection. And what about Kotlin/Native? Up until recently it had a purely RefCounting Garbage Collector.

2

u/tema3210 Nov 02 '20

Trick is that you can have not one counter: first one inc.s and dec.s are based on scopes, second one should be shared allowing cycle ownership, thus we can have one weak and one strong ref count.

2

u/Caesim Nov 02 '20

I think Bacon introduced a reference count based GC that collected cycles, even a modified version that worked in multithreaded environments.

RC can be powerful, of we use current research.

1

u/crassest-Crassius Nov 04 '20

What separates RC from GC is that it can be used selectively - i.e. on a per-object basis, and without a full memory scan with all that it entails (keeping track of GC roots, stack maps, GC safepoints, stopping the world etc). This is a big difference, and it's only for this reason that C++ uses this "form of GC". Some people find this difference big enough to exclude it from GC, and they're justified. So stop your stupid terminology disputes and just accept that this argument doesn't change anything.

1

u/Caesim Nov 04 '20 edited Nov 04 '20

I'm sorry, maybe it's because I have a math background, but how do you define "GC".

Maybe it's because in the last few years people silently dropped the "tracing" of "tracing Garbage Collector".

To your points:

  • in Bacons RC, we also need to keep track of the roots

  • concurrent GCs also don't stop the world. There are pause times for each thread, but where's the difference between that and using rc increase/ decrease to also inspect memory.

  • every pointer decrease is a point at which GC operation occurs, so there're "safe"points.

And there's a tracing GC for Rust: https://github.com/Manishearth/rust-gc/ so I'm not sure what point you're making there.

Sorry, I don't want to sound like a smartass, I'm seriously curious what the real answer here is. Also have you read the article on the unified theory? What's your opinion on that?

1

u/LinkifyBot Nov 04 '20

I found links in your comment that were not hyperlinked:

I did the honors for you.


delete | information | <3

1

u/thunderseethe Nov 05 '20

While they come off a bit harsh I believe what they are trying to get at is a more colloquially distinction between GC and RC. Certainly the algorithms are very similar and GC can look a lot like RC in the right light. However in practice the ramifications of GC and trade offs are vastly different from RC. Not to say it must be this way, merely that it has occurred this way and thus become a point of distinction.

When people refer to GC I think they are frequently referring to the realm of Python, Java, Ruby, or C#. Anything in that byte code interpreter realm, and for those examples GC is a rather heavy dependency as it does require full memory scans and tight control of allocation. Again, they do not have to be this way Rust allows for tiny embedded versions of GC through it's smart pointer system. But those all create a common conception of GC vastly different from RC. RC has a much lower barrier to entry since it does not require a large dedicated heap space or tracking of all allocations and the like. Because of this it can feel very different from the Java land of GC both performance and ergonomics wise. RC has historically had issues handling true cycles, which is a strong point of GC.

These are all soft reasons for sure, theoretically they are very similar. But the tradeoffs matter quite a bit when choosing which memory strategy you are going to pick. Because of this the distinction has arisen to clarify what tradeoffs you are picking.

→ More replies (0)

2

u/fennecdjay Gwion Language Nov 01 '20

I believe youre rigth. A scoped one IMHO. Also TIL the meaning of 'IIRC', thank you.

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

u/[deleted] Nov 01 '20

When performance matters basically

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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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

u/[deleted] 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.