Get the latest tech news

Indices, not Pointers


There is a pattern I’ve learned while using Zig which I’ve never seen used in any other language. It’s an extremely simple trick which - when applied to a data structure - reduces memory usage, reduces memory allocations, speeds up accesses, makes freeing instantaneous, and generally makes everything much, much faster.

It’s used in Zig’s compiler to make very memory-efficient ASTs, and can be applied to pretty much any node-based data structure, usually trees. In practice this isn’t something you normally need to do as many data structures, like an AST, can be freed all at once, but if you need to be able to free individual nodes and still want to use this technique then the obvious solution would be to use a freelist. There are some Zig quirks involved like passing memory allocators and using an enum as an index type but hopefully the general idea is clear.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of Pointers

Pointers

Photo of Indices

Indices

Related news:

News photo

How to store Go pointers from assembly

News photo

Pointers Are Complicated II, or: We need better language specs (2020)

News photo

Crash the GC with Random Values in Unsafe.Pointers