You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Should I use a GC with Zig?Probably not, but it depends on your
use case. A garbage collector is nice in certain scenarios, can make
implementing certain data structures easier (particularly immutable ones),
etc. The nice thing about Zig is you can choose what you want and don't
want in the garbage collector.
Example
conststd=@import("std");
constgc=@import("gc");
constGcAllocator=gc.GcAllocator;
pubfnmain() !void {
varalloc=gc.allocator();
// We'll write to the terminalconststdout=std.io.getStdOut().writer();
// Compare the output by enabling/disabling// gc.disable();// Allocate a bunch of stuff and never free it, outputting// the heap size along the way. When the GC is enabled,// it'll stabilize at a certain size.vari: u64=0;
while (i<10_000_000) : (i+=1) {
// This is all really ugly but its not idiomatic Zig code so// just take this at face value. We're doing weird stuff here// to show that we're collecting garbage.varp=@ptrCast(**u8, tryalloc.alloc(*u8, @sizeOf(*u8)));
varq=tryalloc.alloc(u8, @sizeOf(u8));
p.*=@ptrCast(*u8, alloc.resize(q, 2*@sizeOf(u8)).?);
if (i%100_000==0) {
constheap=gc.getHeapSize();
trystdout.print("heap size: {d}\n", .{heap});
}
}
}
About
Zig-friendly library for interfacing with libgc (bdwgc) -- the Boehm-Demers-Weiser conservative garbage collector