r/ProgrammingLanguages • u/smthamazing • Jun 25 '26
Discussion Is reference counting a trap?
I'm trying to choose a memory management strategy for my language. Since I come from gamedev background, I'm mostly focused on the following:
- Static memory safety guarantees (duh). Which basically implies automatic memory management: if the compiler can prove a leak, it can also insert a
drop()there. - A lot of my code is tight loops in game engine internals or audio processing. Not sure if this rules out GC completely, but I cannot afford any unpredictable pauses - they are very noticeable in games and audio.
- When writing code, I generally don't want to think about allocation strategies. I still choose them consciously per call graph: "module A will just allocate everything with the default strategy", "function B will receive a custom arena allocator and I will just guarantee that it always has enough space". But I don't want to write
allocator.alloc(MyThing, ...)everywhere instead of justnew MyThing(). This leads me to think of some sane default strategy + dynamically scoped allocators via some implicit or effect mechanism. - Not a hard requirement, but ideally I'd like to avoid a mandatory runtime and make sure my approach can work even on tiny devices like Arduino Nano (2KB - 32KB RAM). But I can drop (hehe) this idea if it proves impossible, embedded is not my main target.
All of this leads me to think about reference counting. It sounds rather attractive initially, and on the first glance many of its problems are solvable:
- It incurs some overhead (every deallocation is an int decrement and a check, + you need to keep all these RC counts in memory), but it's very predictable.
- That overhead can be avoided in many cases if the compiler can statically find where RC drops to zero and insert a
drop(). So it will mostly affect objects that persist across frames, like event queues, loggers, etc. - It gets bad when you have cross-thread data sharing and have to use slow atomics for counters. But since I want some form of linear types and ownership semantics anyway, I probably can give explicit choice to programmers: either your value is exclusive to one thread and you can only pass ownership fully; or you wrap it in a "slow"
Arc<...>and incur that overhead consciously (plus some unsafe escape hatches). - Freeing a large object graph can be slow, but this is solvable e.g. by passing ownership to a different thread.
- For strict immutable languages it seems pretty good, see counting immutable beans and Koka's Perceus paper.
What concerns me is that RC seems a rather unpopular choice in programming languages. The only major languages I know that use RC are Python (which is notoriously slow) and Swift, which I have little experience with, but I know that handling of weak and unowned references sometimes gets finicky. This unpopularity makes me think that maybe RC is a dead end for my project.
On top of that concern, pure RC doesn't handle cycles. They are often an architecture smell anyway, but some things like intrusive doubly-linked lists are powerful tools in gamedev, and I wouldn't want to lose them. I wouldn't mind having an optional opt-in GC for cycles specifically, but I'm not sure how to express in the type system that some relation is cyclic (often indirectly) and requires a GC in the context to work. I really want it to be explicit and statically checked.
Another thing is that for games, CPU cache locality is paramount, and RC seems to have issues with that: either you store counters with the objects and your arrays are no longer neatly packed, or you store them separately, and then every inc/dec is a memory read. Maybe it's solvable by selectively using arenas over RC though.
I've heard Nim does something in this space, but I'm not super familiar with that language either, and I'm wary of it having compiler flags for different memory strategies (possibility of ecosystem split, bugs, etc).
Is reference counting a worthwile direction to pursue at all given my requirements, or should I focus on other approaches like a lightweight and more predictable GC, or Rust-like borrowing model? I actually like how borrows work in Rust, but it's a very complex feature, and I'm not confident in my abilities to avoid associated bugs, unsoundness, and variance pitfalls when implementing the compiler.
Any thoughts are appreciated!
22
u/coderpants Jun 25 '26
Take a step back and figure out what is going to bring you joy. What itch are you looking to scratch by creating your own language? That will help guide you as to how deep you want to go.
For my language I went with reference counting for all your reasons, and an additional one - I transpile to C++ and use std::shared_ptr<T> for my GC (optionally throw in some weak_ptr), so I can also easily interoperate between my language and C++ code for both easy building of my standard library, but also as a performance escape hatch.
But you do you.
18
u/Puzzleheaded-Lab-635 Glyph Jun 25 '26
So, I work on Glyph, a strict functional ML that uses reference counting (Perceus-style, à la Koka/Lean 4) as its only memory management strategy. No tracing GC. So I’ll answer from that seat, with the caveat up front: RC works well for us largely because of properties your language probably won’t have. The one you already flagged (cycles) is the load-bearing difference.
Why RC fits Glyph specifically:
We’re immutable and strict, which is why Perceus pays off. The compiler inserts drops at last use, and because values are immutable it can also do reuse analysis (FBIP/FIP). A map over a linearly-used list can mutate cells in place instead of reallocating them. The RC operations that survive are the ones the compiler genuinely cannot prove away, and in practice that tends to be the long-lived stuff (queues, caches, etc.), not the hot path.
Your intuition (“the compiler finds where it drops to zero and frees it”) is basically right, but how much it can elide depends directly on how much aliasing and mutation the language permits. A mutable imperative language gives the analysis far less to work with, so more RC traffic survives into the loops you actually care about.
The other big thing: no cycles can form, by construction. In a strict immutable functional language, you basically cannot build a cycle without an explicit mutable ref cell, and we restrict ref payloads to scalars. So a cycle through the RC heap is literally unrepresentable. Pure RC is therefore complete for us: no cycle collector, ever. We have one designed, but we keep punting it because nothing in the language can actually create a cycle.
This is exactly where your language and mine diverge. Intrusive doubly-linked lists, parent/child scene graphs, observer backpointers (those are cycles, and they’re load-bearing for you, not just a smell you can design away). The moment cycles are first-class, pure RC stops being complete. At that point you’re forced into either:
There’s no free lunch on the cycle question. It costs you something no matter what.
On the rest:
Predictable pauses: yes, this is RC’s real win. Deterministic lifetime, no stop-the-world collector. The honest asterisk is that freeing a large graph can still create a deterministic spike. You can hand that work to another thread, but that is plumbing you now own. For audio, you’ll still want zero allocation in the callback regardless. RC doesn’t save you from that; it just makes the cost more legible.
Tight loops: I’d temper the optimism here. The hardest thing we’ve worked on (months of work, dozens of failed attempts) was making RC leak-free and zero-traffic in tight loops: tail-recursive accumulators, in-place rebuilds, that kind of thing. The programs were correct, but keeping process memory flat instead of churning RC per iteration is still a real frontier. For your hot game/audio loops, I’d bet you end up using arenas rather than per-object RC, exactly as you suspected. That’s fine. They compose: RC for the acyclic 90%, scoped arenas for frame/audio loops.
Scoped allocators via effects: yes, do this. It works. We have algebraic effects, and a dynamically-scoped allocator is one of the most natural things to express that way.
new MyThing()resolves against whatever allocator is in dynamic scope. Noalloc(T, ...)noise at the call site, and you still choose the allocation strategy at the call graph boundary. This is one of the few “want everything, pay almost nothing” wins available, and it’s orthogonal to RC vs GC.Cache locality: real issue, and RC can make it worse. Inline counts break packed arrays; out-of-line counts cost a read per inc/dec. The answer is the arena escape hatch above: keep RC off your packed component data and let ownership live at arena granularity. Don’t try to make RC win the SoA fight.
Atomics across threads: your instinct is right, and it’s roughly where we landed. Values are single-owner by default. Transfer ownership to cross a boundary. Sharing is opt-in and explicit. Our model is actors with disjoint heaps (send transfers, no shared mutable refs across threads), so the common path never touches an atomic counter. Non-atomic RC by default plus an explicit shared wrapper for the rare case is sound.
On RC being “unpopular”: don’t over-read it. That reputation mostly comes from naive RC (Python, etc.). The modern lineage (Koka, Lean 4, Lobster, Roc) is alive and fast. Lean 4 in particular is a serious RC-only language doing heavy compiler/math work. Nim’s problem is not RC itself; it’s the menu of swappable strategies. Pick one and commit.
So, is RC worthwhile for you? For the acyclic majority of your program, genuinely yes: predictable, no libc dependency, tiny-device-friendly in principle, and the overhead lands mostly on long-lived objects. But I would not make it the whole story.
The design I’d point you toward is:
RC as the default for ordinary acyclic heap data, scoped arenas via your effect/implicit mechanism for frame/audio hot paths, and an explicit, statically-visible escape hatch for genuinely cyclic graphs.
Whether that escape hatch is a region-scoped cycle collector or weak-reference discipline is the hard call you cannot dodge. I’d prototype that piece first, because it dictates everything else.
On Rust-style borrows: you do not need full borrow checking to get most of the ownership leverage. We get a lot from lightweight ownership/borrow inference (with no surface lifetime annotations) feeding RC elision. It is not free to implement, but it is a smaller, less treacherous beast than full lifetime-and-variance checking. And it degrades gracefully: a missed inference is an extra RC operation, not a soundness hole.
If full Rust borrows scare you, that middle path is real.
6
u/Dry_Day1307 Jun 25 '26 edited Jun 25 '26
Hi, I’ve built my own programming language and went through this exact rabbit hole when designing its memory management.
Since you are targeting gamedev/audio and want to avoid the sheer complexity of Rust's borrow checker, a hybrid memory layout based on data mutability might be your best bet. Here is how I handle it:
Another approach you could evaluate, which ties into some of the pure functional/immutable concepts you mentioned, is keeping everything in the arena and, whenever a mutation happens, recreating the entire object from scratch in a new memory slot. I evaluated this too: while it makes allocation incredibly fast, it becomes a massive bottleneck if your game loop mutates data frequently. If you have strict static typing and are certain of the data's length, you could technically overwrite it in place inside the arena with extreme care. But honestly, if your code requires heavy mutability, a dedicated object pool is much safer.
Is RC a trap for your use case?
Honestly, for tight audio loops or an Arduino Nano (2KB RAM), probably. RC adds metadata overhead per object, and if you drop the last node of a massive object graph inside a critical frame, you'll still get an unpredictable latency spike from cascading frees.
If you don't want to deal with a full borrow checker, your idea of implicit dynamic allocators via an effect system or context paired with a default compactable arena is a killer sweet spot. It gives you that clean
new MyThing()ergonomics without killing your CPU cache or frames3
u/vmcrash Jun 25 '26
Did you heard about Hylo? It still is some very early state, but it sounds interesting - somehow like Rust's ownership. However, double-linked lists probably might be a problem.
3
u/munificent Jun 25 '26
This isn't strictly true. If there is one remaining reference to an object that in turn contains the sole references to a whole large tree of objects, then decrementing that last reference can trigger a cascade of dereferences, which trigger more deallocations, and so on.
It's really hard to compare latency of tracing GC versus ref-counting because there are so many implementation choices that can affect either. A naive ref-counter that eagerly deallocates on every final dereference might have much worse latency than an incremental tracing GC. But a stop-the-world non-copying GC could have much worse latency than a ref-counter that does deferred ref counting and lazy deallocation.
I wouldn't consider ref-counting itself to be a "cure" for predictability. It depends a lot more on the details of your implementation.
(For my own hobby language which is game-oriented but not super performance-oriented, I intend to do incremental tracing GC. I think that will provide sufficient latency without foisting cyclic reference problems onto users.)
7
u/andreicodes Jun 25 '26
You forgot another popular reference-counted language: modern C++, where every value is wrapped into a unique or shared pointer :D
Games like arenas. You set up an arena for a game frame, allocate everything in it, draw and then drop the whole arena. Similarly in web servers you can have a system that creates an arena per incoming request and drops it after the response is sent. Languages with strict memory policies often struggle with a pattern like this. In Rust popular arena libraries fork standard collections to be able to use them in arena. In GC languages there's often no way to tell the runtime not to traverse individual objects within the arena.
If you think of arenas as data structures owning their data then you can extend this thought process to other data structures, and build your memory system from there. For example, if you decide to ref-count everything then the naive conclusion would be "it's very difficult to work with linked lists, trees and graphs in this language". However, you can provide these data structure in standard library, and the whole point becomes moot! This is what Rust does for some of its APIs. Borrow checker can't split a mutable ref over collection into a collection of mutable for each element: it chokes on the notion that you need multiple mutables projecting into the same collection. But standard library offers APIs for that. Internally it uses raw pointers, a healthy dose of
unsafeand assertions to keep things from blowing up, but outside I callsplit_at_mutand friends and my code looks crispy clean.So, I would approach the problem from usage patterns side instead of selecting something dogmatic. RC is a very good baseline, and some basic escape analysis will let you eliminate half of increments and decrements. Combine them with arenas and data structures hiding weak-pointer complexity from users, and you should have a very good time.
6
u/CandidTomatillo8874 Jun 25 '26
Memory management is just a can of worms, no matter how you do it. One possible strategy, if you want probably the best correctness and latency guarantees - is called heap less or tiger-style programming. Instead of recycling memory at runtime (which can introduce heap fragmentation, memory corruption, performance problems and so on) you just allocate all of your memory statically up-front and define fixed-upper bounds for every resource. This allows you to potentially batch allocate the whole program as one block of memory ahead of time, avoiding requests to the heap at runtime (literally zero).
The downside of this strategy is that now you cannot use dynamic arrays - instead every upper bound must be budgeted ahead of time. This is actually an approach that is standard practice in embedded programs, because any latency from allocating to the heap could be a safety problem (and also generally thinking about memory upper bounds on low-memory embedded hardware is good practice).
The Rust borrow-checker is a neat idea, but it does not allow self-referential structures, so it is difficult to do this kind of memory management strategy in Rust. You end up instead with many dynamic arrays, small heap allocations and fragmenting the heap, just to connect things together.
The other benefit with fixed allocations is that then you can add additional correctness guarantees in the type system - for example you can add typed indices (similar to Ada) that are bounded to be within the range of the arrays at compile time (The upper bound can be made part of the index type).
Just throwing this out there if you are thinking about making things for embedded. If you have a look at style guides for embedded like the MISRA standards and the NASA 10 rules you will also see similar things.
4
u/thehenkan Jun 25 '26
It's possible to mix RC with a borrowing model to prevent RC traffic in hot loops. Swift has been introducing this in later versions: take a look at Span and ~Escapable. These can place a statically checked borrow on a reference counted object, and then pass around its internals with no overhead for the duration of the borrow. It doesn't solve the issue with cycles though.
4
u/Tasty_Replacement_29 Bau Jun 25 '26
My language also uses reference counting, and where speed is very important, a simple form of ownership / borrowing (here described in more detail).
A few points to what you wrote:
1
u/FISHARM1 Jun 25 '26
You say you write a lot of audio processing and game development code, I immediately think of an arena allocator. Have you looked into that?
3
u/carangil Jun 28 '26
I'm using reference counting on a stack machine, and a series of pointer rules:
Rules for counted references:
Rules for uncounted references
The rules let me assume that when an uncounted reference is passed to a function... no matter what that function does, it cannot escape because those references can't be stored anywhere, or returned. It's on the stack for a one-way path to deeper nodes of the AST. And it's guaranteed to be a valid pointer for the entire duration of that function call, because that borrowed value, which might contain the last counted reference to that object, is on the stack until that subtree of the AST is done running.
This is enforced by virtual machine and type system; counted and uncounted references are different types, and they each only support a subset of operations. (There is no 'free' instruction that accepts an uncounted reference. There is no store instruction for counted references: to store a counted reference in a variable you swap with it, and then do something with the old value (such as free)
What about reference cycles: The language encourages the use of arrays or trees, but not graphs. If you want a graph, that's an array of graph nodes, with indices instead of pointers. That does kind of put it on the user to deal with that, but the point is the user program will just throw the whole graph away at once. The language wants you to use arenas and contiguous arrays of data. I am considering adding a special Arena structure, which is an array with some helper functions to track used vs unused elements. (Will probably use reference counting in here too.)
2
u/Manny__C Jun 28 '26
By the way, you can get away with cycles and reference counting if you introduce weak references.
For instance, a doubly linked list could be designed such that .next increases strong count and .prev does not (i.e. is a weak reference).
3
u/Public_Grade_2145 Jun 25 '26
I've ported my scheme interpreter over RP2040. It is not a VM but a naive tree-walk CEK machine. I use Cheney GC, and use 192kb heap size. It is doable. I don't have heroic optimization beside tagged pointer.
Actually, MCUs like RP2040 are simple hardwares that you only have SRAM and optimizing for cache doesn't make sense here. But when it comes to hosted implementation, say on Linux AMD64, compacting GC actually can help since it compact the heap into a tigther contiguous space.
In addition, runtime with Cheney GC is just bump allocator which is easy to implement.
I'm not familiar with reference counting and real time applications so I can't comment anything about these.
Project link: https://github.com/taimoon/scheme-interpreter
3
u/alphaglosined Jun 25 '26
You can use GC in games, but you have to disable its collection during normal play. It's best used for housekeeping tasks. It also works with audio, but the play thread should not be registered with it.
RC is perfect for system handles, where you must cleanup and quite importantly, will not have cycles. For cycles, yes you need a GC to resolve this, this was solved in the 80's. But keep in mind the important property of RC, you have a counter with an add and sub action on it.
Ownership transfer systems are a form of RC, where the max on the counter is 1. You did not mention it, although you mentioned borrow checkers. People quite often misunderstand that an ownership transfer system is separate from the borrow checker.
For games you have a very important property, the frame. A simple bump the pointer allocator can work with it, as long as you track which frame you are working with.
There are multiple valid options that solve different lifetime requirements; you may not want to pick only one. I'm still not entirely sure what the game dev frame-based allocator would look like; I have yet to see language integration for it.
2
u/initial-algebra Jun 25 '26
GC pauses are not entirely unpredictable. Either they're triggered by trying to allocate when out of memory, or they're triggered manually. The simplest way to prevent a GC pause from interrupting a sensitive task is to not allocate during that task. Real-time audio processing code is so sensitive that you cannot even use manual memory management such as
malloc/free, let alone GC, in the first place. Game engine code is far less sensitive, so you can allocate as long as you can be reasonably sure that you won't run out of memory. Actually, a GC would be better than MMM in this case, because a successful allocation is just a pointer bump (assuming a compacting collector). If you run manual collections every frame when there is nothing else to do (e.g. waiting on the GPU to do some rendering work), and you don't have any memory leaks, then, short of actually exhausting memory by allocating faster than you can collect, you shouldn't run into any noticeable pauses.Of course, the situation becomes more complicated when you introduce concurrency, because a sensitive task that doesn't allocate but still accesses GC-owned memory cannot run concurrently with (compacting) GC. In other words, a sensitive task has no GC safepoints, which are points where GC pauses are allowed to occur. This means that, if an allocation would cause GC, it will be blocked until all sensitive tasks are complete, which might be a lot worse than a normal GC pause!
1
u/david-1-1 Jun 25 '26
Do you expect multiple owners of a block? If there's always just one owner, it's like RC limited to 1 or 0. Smart pointers to memory can be allocated, freed, or transferred to another owner. Fast, for gaming.
1
u/trijezdci_111 Jun 25 '26
You do NOT need to decide the memory management scheme at the language level. You can shift the decision into the libraries that provide types, on a per library type basis.
We have done this in a modern revision of Modula-2. In C and also classic Modula-2, there are allocation and deallocation hooks/macros built into the language, but the implementation is in a library. The compiler simply maps the macros to the library functions. This then permits the library to be replaced. C's Boehm collector is based on this principle. This way, the choice is already in the hands of users, but it is all-or-nothing, either or. You can still do better.
In a modern revision of Modula-2, my co-author and I have extended the basic principle of a user replaceable storage library. We introduced a second level that works on a per library basis. Then we added built-in hooks for new, retain and release functions for this level.
The global level library provides two functions for raw allocation and deallocation. Different alternatives of this library can be provided, all with identical interface. Each library provides two functions for block allocation and deallocation. In a variant that does GC, the deallocation function would not need to be called, or it could be omitted altogether. The functions are then explicitly linked to the built-in macros/primitives.
INTERFACE MODULE Storage;PROCEDURE [ALLOC] Allocate ( VAR p : CAST ADDRESS; size : LONGCARD );PROCEDURE [DEALLOC] Deallocate ( VAR p : CAST ADDRESS );END Storage.The names in square brackets tell the compiler which built-in macros/primitives the functions are to be hooked into.
At the library level, each library type implements one, two or three functions, depending on whether the library is intended for manual memory management, GC, RC or ARC.
INTERFACE MODULE DynString;TYPE DynString = OPAQUE; (* definition in implementation module *)PROCEDURE [NEW] New ( VAR s : DynString );PROCEDURE [NEW+] NewWithInit ( VAR s : DynString; init : ARRAY OF CHAR );PROCEDURE [RETAIN] Retain ( VAR s : DynString );PROCEDURE [RELEASE] Release ( VAR s : DynString );(* other facilities *)END DynString.The names in square brackets again tell the compiler which built-in syntax the functions are to be hooked into. For the NEW syntax there are two forms ...
NEW str;andNEW str := "the quick brown fox jumps over the lazy dog.\n";and for refcounting syntax there are ...
RETAIN str;andRELEASE str;The compiler then replaces these syntax forms with the hooked in library calls. The library implementation uses the hooks for ALLOC and DEALLOC which the compiler then replaces with their hooked in library calls.
If automatic reference counting (ARC) is desired, this can be done by marking the library with an attribute in the module header. We did this via pragma
INTERFACE MODULE DynString <*ARC*>;but it could also be done as proper language syntax. For ARC, the language will need to provide additional attributes for strong and weak references. We provide those also via pragmas
<*OWNER*>and<*BORROWER*>.VAR myStr : DynString <*OWNER*>;PROCEDURE find( CONST s : DynString <*BORROWER*>; search : ARRAY OF CHAR ) : INTEGER;Likewise, if your library requires GC, you can mark the module with an attribute for GC. This way the compiler can ascertain that the appropriate memory management library is used.
INTERFACE MODULE DynString <*GC*>;This way, you can support all four possibilities in the language: garbage collected, automatic reference counting, manual reference counting and manual memory management. For each type you choose the most appropriate memory management scheme. For time critical data types you can avoid garbage collection, and possibly ARC, too. You are not paining yourself into a corner.
For a more in-depth description you can consult our language specification at
https://github.com/m2sf/m2bsk/wiki/Language-Specification-(10)-:-Syntax-Binding
1
u/Mason-B Jun 25 '26 edited Jun 25 '26
On this point, I'd strongly encourage you to read this paper that lays out how pure automatic reference counting and garbage collection are duals of each other, and how hybrid systems are a spectrum between them. There is a lot of noise from orthogonal features around this in the direction of complexity (Rust's borrow checker, Perceus' functional but in place), which are notable technologies. But unless you want to be a leading research language on those topics (like Rust or Perceus) you need to pick a general solution, meaning that you have to make choices and tradeoffs here. The paper lays out the high level decisions that must be made.
1
u/SwedishFindecanor Jun 25 '26 edited Jun 26 '26
The technique of inferring ownership and borrowing from RC automatically to speed up RC has actually been invented multiple times. It is also called (lifetime) subsumption, but I think using the same terminology as Rust lifetimes has become the most mainstream. The owned xor mutable rule could be relaxed though, except for when objects can be shared by multiple threads. Besides nesting, when two references' lifetimes can be proven to overlap, they could be replaced with a single lifetime. (mentioned in Ritzau 03. Is there an older paper?).
I'd recommend reading also Memory Management in Lobster because it contains a quite practical description of how that language's compiler does it.
One possible language feature (which some on this sub are exploring) is to have automatic inference by default, but have strong ownership as an option: programmers would then be able to first develop something that works with just RC and optimise the program with ownership later.
Another technique is deferred update within a subroutine. First add to the counter in memory to keep the object alive. Then update only a local proxy counter when creating/destroying references. Last, adjust the counter in memory from the local counter, and deallocate the object if necessary. This can optimise some cases that ownership inference doesn't. It should be done as a late optimisation, after inlining, if you have that. (I forgot which paper I read about this in)
Besides these optimisations, the fastest RC-GC algorithms are the deferred algorithms where objects don't have to be reclaimed as soon as they become unreachable. Those can be quite complex, however.
You have already identified the trap of allowing race conditions to references in memory, which therefore require costly atomic updates and to their counters. Another trap would be to design your language to guarantee a deterministic destructor call sequence, or so that you can't optimise objects without destructors — because then deferred collecting of any kind would be impossible to implement in the future.
Could you think of a way to make them part of the language or a special library?
If they are in the language, then users would simply have to trust that it's internal implementation is memory-safe. Several containers in Rust's standard library are written in "unsafe" code that avoids the language's memory management altogether, and people then just have to trust that code to have been audited and tested more thoroughly than other code.
Then you would need to count only external references (i.e. not links/edges). Either require that every such object always belongs to a collection, or that every detached object is in a special state which is treated differently.
I have played with the idea of having data structures be declarative. Instead of writing code that manipulates a data structure and have assertions and proving memory-safety, declare the legal states and let the compiler generate the code that transforms the data structure from one state to another. I'd think the resulting machine code could be just as tight as well-written code, but simpler to write — and proven memory-safe. I have not worked on this much myself yet. It is at the intersection of graph transformation and type-state ... but I'd preferably want to reduce this down to something very simple without too much theoretical baggage. It needs recursion in transformation and some decision about how to deal with external references (if they are going to be allowed at all).
| On top of that concern, pure RC doesn't handle cycles.
The original Weak pointer was actually from an algorithm that categorised pointers as Strong/Weak at run-time, but flaws in the algorithm were found, so the static approach became used instead.
In Brandt et al 2014 the flaws had been fixed, and developed into Strong/Weak/Phantom, where the Phantom state exists only during a cycle detection phase. All three states are internal to the algorithm: the user does not have to declare anything as
weakorunowned. I don't know why this algorithm isn't more known ... I think a possible optimisation could be to to specialise the tracing function for each start node type, so that traces could finish early. (I think I've seen that approach elsewhere for another cycle detection algorithm, but I dunno...)1
u/erez27 Jun 25 '26
It doesn't sound like the worst plan. You could still add a simpler variation of burrow checking or reference optimizations, just enough to make the common and simple cases even faster.
1
u/Ok-Scheme-913 Jun 26 '26
You have clearly done your homework on the topic.
One note I would add is that the tracing GC line still has many interesting contenders, though implementing it well-enough is far from trivial.
Of course you would have to visit 'The Source', the JVM for that. ZGC managed to decouple the heap size from the world pause length, so it can deliver predictable max pause times even with lots of garbage.
On top, generational GCs have excellent allocation performance, only beaten by custom arena allocation (you can just have a big array and a pointer per thread, and simply bump the pointer up on each allocation. No locking, nothing needed. When it's sufficiently full you just copy the still reacable objects out of it and set the pointer to the zero index, having deleted non-reachable objects for completely free)
And there are many similar performance wins if you forego the requirement that pointers are "pinned" (not in a rust meaning, but as per the compiler). If the runtime may move these under the hood there are novel optimizations possible, and paired with immutable value types that have no identity, you don't have to pay all that much for extra memory use either.
1
u/EggplantExtra4946 Jun 27 '26
If you go with the custom allocator route, are you going to implement dynamic scoping using a hidden argument passed through every function, or with a global variable? Assuming that old values are saved to and restored from the call stack.
1
u/fdwr Jul 08 '26
Note that C++ game engines using DirectX API's are nano-COM based for resources, which are certainly reference counted. You could argue that's not part of the language, and you could possibly even say that
std::shared_ptris not part of the core language since it's in a library rather than built-in, but it's only one#includeorimport stdaway. Then Rust hasstd::rc::Rc. Add to that Delphi, Perl, PHP, TCL... So, I'm not saying you should or should not use reference counting, but I'd argue reference counting is common in lots of languages, one way or another.