Skip to content

Zig Performance

Zig gives you a lot of control over speed, but control isn’t the same as speed. Most slow programs are slow in one or two places, and you can’t guess which ones: you have to measure. This page shows how to time code with the 0.17 clock API, why the build mode matters more than anything else, a trap that makes benchmarks lie, and the two changes that most often pay off: allocating less, and laying out your data so the CPU can read it quickly.

To time a piece of code, read a clock before and after it. In Zig 0.17 clocks go through std.Io, like files and the network, so you need io from init.io:

const std = @import("std");
fn countPrimes(limit: u32) u32 {
var count: u32 = 0;
var n: u32 = 2;
while (n < limit) : (n += 1) {
var is_prime = true;
var d: u32 = 2;
while (d * d <= n) : (d += 1) {
if (n % d == 0) {
is_prime = false;
break;
}
}
if (is_prime) count += 1;
}
return count;
}
pub fn main(init: std.process.Init) void {
const io = init.io;
const start = std.Io.Timestamp.now(io, .awake);
const primes = countPrimes(2_000_000);
const elapsed = start.untilNow(io, .awake);
std.debug.print("{d} primes\n", .{primes});
std.debug.print("took {d} ms ({f})\n", .{ elapsed.toMilliseconds(), elapsed });
}

You’ll see something like:

148933 primes
took 535 ms (535.737ms)
  • std.Io.Timestamp.now(io, .awake) reads a clock. .awake is a monotonic clock: it only moves forward, so it’s the right one for measuring. Don’t use .real (the wall clock) for timing: it can jump when the system adjusts the time.
  • start.untilNow(io, .awake) gives a std.Io.Duration, the time since start.
  • A Duration has toMilliseconds(), toMicroseconds() and toSeconds(), and it prints itself nicely with {f}.

Older code and tutorials use std.time.Timer or std.time.nanoTimestamp(). Those are gone in 0.17: the clocks moved into std.Io.

Before you change a single line, check how you’re building. zig run and zig build use the debug mode by default, which is built for finding bugs, not for speed. Here’s the same prime counter in all four modes:

Mode Command Time (our VM)
debug zig run primes.zig 535 ms
safe zig run -O safe primes.zig 344 ms
fast zig run -O fast primes.zig 345 ms
small zig run -O small primes.zig 356 ms

For this small loop, every optimized mode is about the same, and debug is about 1.5 times slower. On code that allocates a lot, the gap is far bigger, as you’ll see in a moment. So the first rule: never judge speed from a debug build. Zig Build Modes explains what each mode keeps and removes, and the language reference on optimization modes has the full list.

safe keeps the safety checks (overflow, bounds, unreachable) and still optimizes. It’s a good default for programs you ship, and it’s often close to fast, like here. Switch to fast when you’ve measured that the checks cost something that matters.

The trap: the compiler can delete your benchmark

Section titled “The trap: the compiler can delete your benchmark”

Here’s a mistake almost everyone makes once. You only want the time, so you throw the result away:

const start = std.Io.Timestamp.now(io, .awake);
_ = countPrimes(2_000_000);
const elapsed = start.untilNow(io, .awake);
std.debug.print("took {f}\n", .{elapsed});

In a debug build this prints about 590 ms. In a fast build, when we ran it:

took 110ns

Counting 148,933 primes in 110 nanoseconds isn’t fast, it’s impossible. The optimizer saw that nobody uses the result, and countPrimes has no side effects, so it deleted the whole call. Use the result (print it, like the first example), or hand it to std.mem.doNotOptimizeAway:

std.mem.doNotOptimizeAway(countPrimes(2_000_000));

With that line, the fast build measured 346 ms again. Whenever a speedup looks too good to be true, check this first.

Asking an allocator for memory is much slower than using memory you already have. In a loop that runs thousands of times, a fresh allocation per round adds up. Compare making a string with the heap each time against reusing one buffer on the stack:

const std = @import("std");
const rounds = 200_000;
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
// Version 1: a fresh heap allocation every time.
var t = std.Io.Timestamp.now(io, .awake);
var len_a: usize = 0;
for (0..rounds) |i| {
const line = try gpa.print("item {d} costs {d} coins", .{ i, i * 3 });
defer gpa.free(line);
len_a += line.len;
}
const time_a = t.untilNow(io, .awake);
// Version 2: one buffer on the stack, reused every time.
t = std.Io.Timestamp.now(io, .awake);
var len_b: usize = 0;
var buf: [64]u8 = undefined;
for (0..rounds) |i| {
const line = try std.mem.print(&buf, "item {d} costs {d} coins", .{ i, i * 3 });
len_b += line.len;
}
const time_b = t.untilNow(io, .awake);
std.debug.print("allocate each time: {d} bytes in {f}\n", .{ len_a, time_a });
std.debug.print("reuse one buffer: {d} bytes in {f}\n", .{ len_b, time_b });
}

What we measured:

Mode Allocate each time Reuse one buffer
debug 3.416 s 59 ms
safe 102 ms 8 ms
fast 18 ms 5 ms

Two lessons in one table. First, reusing the buffer wins in every mode, three to four times in fast and much more elsewhere. Second, look at that debug column: init.gpa in debug builds is the safety-checking allocator, which records a stack trace for every allocation so it can report leaks. That’s what you want while hunting bugs, and it’s also why a debug benchmark of allocation-heavy code tells you almost nothing.

Ways to allocate less, roughly from easiest to most work:

  • Use a stack buffer when you know a size limit, like std.mem.print(&buf, ...) above.
  • Reuse a list: call list.clearRetainingCapacity() instead of making a new ArrayList each round. It empties the list but keeps its memory.
  • Reserve up front: try list.ensureTotalCapacity(gpa, n) when you know roughly how many items are coming, so the list grows once instead of many times.
  • Use an arena per round and reset(.retain_capacity) it, as in Zig Arena Allocator.

Data-oriented design: think about how data sits in memory

Section titled “Data-oriented design: think about how data sits in memory”

The CPU doesn’t read memory one byte at a time. It pulls in a small block (a cache line, 64 bytes on most machines) and keeps it close by. Code is fast when the bytes it needs next are already in a block it just fetched.

Now picture a list of game monsters, where each one has a name, a position and hit points. In an ArrayList(Monster), they’re stored one whole monster after another. That’s called an array of structs. If a loop only needs the hit points, it still drags every name and position through the cache, because they sit in between.

The other layout is a struct of arrays: all the hit points together, all the names together, and so on. A loop over hit points then reads only hit points. The standard library does this for you with std.MultiArrayList:

const std = @import("std");
const Monster = struct {
name: []const u8,
hp: u32,
alive: bool,
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var monsters: std.MultiArrayList(Monster) = .empty;
defer monsters.deinit(gpa);
try monsters.append(gpa, .{ .name = "slime", .hp = 10, .alive = true });
try monsters.append(gpa, .{ .name = "bat", .hp = 4, .alive = false });
try monsters.append(gpa, .{ .name = "troll", .hp = 80, .alive = true });
// One field at a time: a plain slice of just that field.
var total: u32 = 0;
for (monsters.items(.hp)) |hp| total += hp;
std.debug.print("total hp: {d}\n", .{total});
// Several fields side by side.
for (monsters.items(.name), monsters.items(.alive)) |name, alive| {
if (alive) std.debug.print("{s} is alive\n", .{name});
}
// Or the whole struct back, put together for you.
const third = monsters.get(2);
std.debug.print("monster 2: {s} with {d} hp\n", .{ third.name, third.hp });
std.debug.print("one Monster struct: {d} bytes\n", .{@sizeOf(Monster)});
}

Output:

total hp: 94
slime is alive
troll is alive
monster 2: troll with 80 hp
one Monster struct: 24 bytes

You use it almost like an ArrayList: .empty, append(gpa, ...), deinit(gpa). The difference is items(.hp), which gives you a []u32 of just the hit points. Each Monster struct is 24 bytes, but a loop over items(.hp) reads only 4 bytes per monster. As a bonus, the bool fields are packed together too, instead of each one wasting padding inside the struct.

Does it matter? We summed the hit points of one million monsters (each with a 48-byte name array, so the struct is 60 bytes), three rounds each:

const std = @import("std");
const Monster = struct {
name: [48]u8,
x: f32,
y: f32,
hp: u32,
};
const count = 1_000_000;
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
var list: std.ArrayList(Monster) = .empty;
defer list.deinit(gpa);
var multi: std.MultiArrayList(Monster) = .empty;
defer multi.deinit(gpa);
for (0..count) |i| {
const m: Monster = .{ .name = @splat('m'), .x = 0, .y = 0, .hp = @intCast(i % 100) };
try list.append(gpa, m);
try multi.append(gpa, m);
}
for (0..3) |_| {
var t = std.Io.Timestamp.now(io, .awake);
var total_a: u64 = 0;
for (list.items) |m| total_a += m.hp;
const time_a = t.untilNow(io, .awake);
t = std.Io.Timestamp.now(io, .awake);
var total_b: u64 = 0;
for (multi.items(.hp)) |hp| total_b += hp;
const time_b = t.untilNow(io, .awake);
std.debug.print("ArrayList: {d} in {f} MultiArrayList: {d} in {f}\n", .{ total_a, time_a, total_b, time_b });
}
}

With zig run -O fast, you’ll see something like:

ArrayList: 49500000 in 5.107ms MultiArrayList: 49500000 in 811.459us
ArrayList: 49500000 in 4.716ms MultiArrayList: 49500000 in 792.96us
ArrayList: 49500000 in 5.043ms MultiArrayList: 49500000 in 842.295us

Same answer, about six times faster, from changing only the container. Notice that both totals are printed: that’s what keeps the optimizer from deleting the loops.

This isn’t a rule to switch every list. A struct of arrays wins when loops touch a few fields of many items. When you usually need the whole item at once, a plain ArrayList is simpler and just as good. The Zig compiler uses it too: its syntax tree (std.zig.Ast) stores tokens and nodes in MultiArrayLists.

Timing single blocks works when you already suspect a spot. When you don’t, use a profiler, a tool that watches the running program and tells you which functions take the time. Zig produces normal native programs with normal debug info, so the usual tools for your system work: perf on Linux, Instruments on macOS, and so on. Build with -O fast or -O safe for profiling (not debug, for the reasons above), and keep debug info so the profiler can show function names.

A good habit loop: profile, find the one hot spot, change one thing, measure again, keep the change only if the numbers say so.

Fill a slice of one million u32 with random numbers (std.Random.DefaultPrng), time std.mem.sort on it, and compare debug with fast.

Hint: var prng: std.Random.DefaultPrng = .init(42); const random = prng.random(); then random.int(u32). Sort with std.mem.sort(u32, numbers, {}, std.sort.asc(u32)). Print a value from the sorted slice so the sort can’t be removed.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const gpa = init.gpa;
const numbers = try gpa.alloc(u32, 1_000_000);
defer gpa.free(numbers);
var prng: std.Random.DefaultPrng = .init(42);
const random = prng.random();
for (numbers) |*n| n.* = random.int(u32);
const start = std.Io.Timestamp.now(io, .awake);
std.mem.sort(u32, numbers, {}, std.sort.asc(u32));
const elapsed = start.untilNow(io, .awake);
std.debug.print("sorted {d} numbers in {f}\n", .{ numbers.len, elapsed });
std.debug.print("smallest: {d}, largest: {d}\n", .{ numbers[0], numbers[numbers.len - 1] });
}

You’ll see something like this with zig run sort.zig (debug):

sorted 1000000 numbers in 577.118ms
smallest: 8581, largest: 4294966518

And with zig run -O fast sort.zig:

sorted 1000000 numbers in 104.006ms
smallest: 8581, largest: 4294966518

About five times faster on our VM, from one flag. The seed 42 makes the numbers the same every run, so only the time changes.

This loop makes and frees a new string every round. Rewrite it to reuse a single std.ArrayList(u8).

for (1..4) |i| {
const line = try gpa.print("item {d} costs {d} coins", .{ i, i * 3 });
defer gpa.free(line);
std.debug.print("{s}\n", .{line});
}

Hint: make the list before the loop, call clearRetainingCapacity() at the start of each round, and write into it with try line.print(gpa, fmt, args).

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var line: std.ArrayList(u8) = .empty;
defer line.deinit(gpa);
for (1..4) |i| {
line.clearRetainingCapacity();
try line.print(gpa, "item {d} costs {d} coins", .{ i, i * 3 });
std.debug.print("{s}\n", .{line.items});
}
}

Output:

item 1 costs 3 coins
item 2 costs 6 coins
item 3 costs 9 coins

The list allocates in the first round and then keeps its memory, so later rounds don’t ask the allocator for anything. There’s one deinit at the end instead of a free per round.

Store three points (x, y and a label) in a std.MultiArrayList and find the largest x by looping over items(.x) only.

Hint: start with var points: std.MultiArrayList(Point) = .empty; and use @max inside the loop.

Show solution
const std = @import("std");
const Point = struct {
x: f32,
y: f32,
label: []const u8,
};
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var points: std.MultiArrayList(Point) = .empty;
defer points.deinit(gpa);
try points.append(gpa, .{ .x = 1, .y = 2, .label = "a" });
try points.append(gpa, .{ .x = 5, .y = 1, .label = "b" });
try points.append(gpa, .{ .x = 3, .y = 7, .label = "c" });
var max_x: f32 = 0;
for (points.items(.x)) |x| max_x = @max(max_x, x);
std.debug.print("largest x: {d}\n", .{max_x});
}

Output:

largest x: 5

The loop only ever touches the x values, which sit next to each other in memory. With three points that makes no difference, but the code is the same for three million.

  • Measure before you optimize. Time code with std.Io.Timestamp.now(io, .awake) and untilNow, and print the Duration with {f}.
  • Never judge speed from debug. Use -O safe or -O fast; debug allocations are especially slow on purpose.
  • Use the result of what you time, or the optimizer may delete it. std.mem.doNotOptimizeAway helps.
  • Allocate less in hot loops: stack buffers, clearRetainingCapacity, ensureTotalCapacity, arenas.
  • A struct of arrays (std.MultiArrayList) is much faster when loops read a few fields of many items.
  • In Zig 0.17, LLVM’s loop vectorization is switched off, so write @Vector code yourself where SIMD matters.

Next up: Zig Inline Assembly, for the rare moments when you need one exact CPU instruction.

Quick check

1. Which clock should you use to time a piece of code?
2. Your fast benchmark says a heavy function took 110 nanoseconds. What is the most likely reason?
3. Why is allocation-heavy code so much slower in a debug build?
4. When does std.MultiArrayList beat a plain ArrayList of structs?