Zig Build Modes
The same Zig code can be compiled four different ways, called build modes (or optimization modes). One is for writing and debugging, one is a careful release, one goes for raw speed and one for the smallest file. You don’t change your code to switch between them: you pass one flag. This page shows what each mode keeps and what it throws away, with real file sizes and build times measured for this page, so you can pick the right one with your eyes open.
Everything here was checked with Zig 0.17.1, on a 4-core Linux x86-64 machine.
The four modes
Section titled “The four modes”| Mode | Safety checks | Optimized | Typical use |
|---|---|---|---|
debug (default) |
on | no | Writing code, running tests, debugging. |
safe |
on | yes | Releases where a bug should stop the program, not quietly misbehave. |
fast |
off | yes | Code where speed matters most and that’s well tested. |
small |
off | yes, for size | Small downloads: WebAssembly, embedded devices, tiny tools. |
“Safety checks” are the runtime checks you’ve met throughout this tutorial: integer overflow, out-of-bounds indexes, unreachable being reached, unwrapping a null with .?, and the rest of illegal behavior. In debug and safe they stop the program with a clear message. In fast and small they’re gone.
Choosing a mode
Section titled “Choosing a mode”zig run, zig build-exe and zig test take -O:
zig run main.zig # debug, the defaultzig build-exe main.zig -O safezig build-exe main.zig -O fastzig test main.zig -O small # tests can run in any mode tooIn a project with a build.zig, the template’s standardOptimizeOption gives you -Doptimize (see Zig Build System):
zig build -Doptimize=safezig build run -Doptimize=fastzig build --release=small # the same as -Doptimize=smallPlain zig build --release only works if the project’s build.zig names a preferred mode. Otherwise Zig asks you to choose:
the project does not declare a preferred optimization mode. choose: --release=fast, --release=safe, or --release=smallWatching safety checks come and go
Section titled “Watching safety checks come and go”Here’s a program with a bug: a u8 holds 0 to 255, and it adds 250 and 10. The extra is computed from the number of arguments, so the compiler can’t see the overflow coming and has to catch it at runtime.
const std = @import("std");
pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); // The number of arguments is only known when the program runs. var x: u8 = 250; x += @intCast(args.len * 10); std.debug.print("x = {d}\n", .{x});}Run it in each mode, with no arguments (so args.len is 1 and the extra is 10):
zig run overflow.zig -O debugzig run overflow.zig -O safezig run overflow.zig -O fastzig run overflow.zig -O smallYou’ll see something like this (the stack traces are trimmed):
== debugthread 8097 panic: integer overflowoverflow.zig:7:7: 0x11e4321 in main (overflow.zig) x += @intCast(args.len * 10); ^== safethread 8102 panic: integer overflowoverflow.zig:7:7: 0x1027a61 in posixCallMainAndExit (overflow) x += @intCast(args.len * 10); ^== fastx = 204== smallx = 4debug and safe both catch the bug and point at the exact line. fast and small don’t check, so the program keeps going with a wrong number. And look closely: they don’t even agree on which wrong number. Overflow without a check is undefined behavior: the optimizer is allowed to assume it never happens, so the result can be anything, and it can change when you change unrelated code or update Zig. That’s why a check is so valuable while you’re developing.
The same goes for std.debug.assert(ok). In debug and safe, a false assert panics. In fast and small, it isn’t checked at all: the optimizer treats it as a promise that ok is true and may build on that promise.
Sizes and build times
Section titled “Sizes and build times”Here’s the classic hello world, built in each mode:
const std = @import("std");
pub fn main() void { std.debug.print("Hello, World!\n", .{});}Output:
Hello, World!These are the sizes of the resulting Linux x86-64 program with Zig 0.17.1, measured for this page. “Stripped” means built with -fstrip, which leaves out the debug information (the part that turns addresses back into file names and line numbers).
| Mode | File size | Stripped (-fstrip) |
Build time |
|---|---|---|---|
debug |
10.4 MB | 2.9 MB | 0.4 s |
safe |
3.7 MB | 301 KB | 19 s |
fast |
4.0 MB | 224 KB | 18 s |
small |
136 KB | 136 KB | 2.7 s |
A few things stand out:
- Most of a big binary is debug information.
smallstrips it by default; the other modes keep it unless you ask. debugbuilds in well under a second, release modes take much longer. On x86-64,debuguses Zig’s own code generator, which is built for speed of compiling, while the release modes go through LLVM, which spends time optimizing. That’s the main reasondebugis the default: you rebuild constantly while working.fastandsafeare close. Stripped,fastcomes out smaller here (it carries no safety checks), but with debug info it’s slightly bigger. Small differences like that depend on the code, so measure your own program if size matters.
Treat these as rough numbers: they change with your machine, your OS, your code and the Zig version. A hello world that prints with std.debug.print also pulls in Zig’s I/O and error-reporting code. A program with an empty main built in small was just 4.8 KB here, so the size depends a lot on what you use.
What else changes between modes
Section titled “What else changes between modes”Safety checks are the big difference, but not the only one. Everything in this table was tried with 0.17.1:
debug |
safe |
fast |
small |
|
|---|---|---|---|---|
| Panic messages | with stack trace | with stack trace | with stack trace | message only (“stack tracing is disabled”) |
Error return traces from main |
yes | no, just error: X |
no | no |
Leak report from init.gpa |
yes | yes | no | no |
undefined memory filled with 0xaa |
yes | yes | no | no |
| Debug info in the file | yes | yes | yes | no |
The leak report comes from init.gpa (see Zig Main & Init): in debug and safe it’s a checking allocator, and in fast and small it switches to a faster one that doesn’t check. The 0xaa filling helps you spot uninitialized memory while debugging; in release modes the memory just holds whatever was there. Zig Error Return Traces shows how to turn traces on in other modes when you want them.
Checking the mode in your code
Section titled “Checking the mode in your code”@import("builtin") tells your code which mode it’s being compiled in. The value is known at compile time, so code in a branch that doesn’t match isn’t compiled at all.
const std = @import("std");const builtin = @import("builtin");
pub fn main() void { std.debug.print("mode: {t}\n", .{builtin.optimize}); std.debug.print("safety checks: {}\n", .{builtin.optimize.runtimeSafety()}); if (builtin.optimize == .debug) { std.debug.print("debug build: printing extra details\n", .{}); }}Output:
mode: debugsafety checks: truedebug build: printing extra detailsBuild it with -O fast and you get mode: fast, safety checks: false, and no third line. builtin.optimize is a std.lang.Optimize, an enum with the four values .debug, .safe, .fast and .small. In older code you’ll see builtin.mode: it’s the same thing under its deprecated name.
@setRuntimeSafety: per block, not per program
Section titled “@setRuntimeSafety: per block, not per program”Sometimes one part of a program needs different rules. @setRuntimeSafety(true) keeps the checks on inside one block or function even in a fast build, and @setRuntimeSafety(false) turns them off inside one block even in a debug build.
const std = @import("std");
fn addChecked(a: u8, b: u8) u8 { @setRuntimeSafety(true); // keep the overflow check, even in fast builds return a + b;}
fn addUnchecked(a: u8, b: u8) u8 { @setRuntimeSafety(false); // no check here, even in debug builds return a + b;}
pub fn main(init: std.process.Init) !void { const args = try init.minimal.args.toSlice(init.arena.allocator()); const extra: u8 = @intCast(args.len * 10); // 10 when there are no arguments std.debug.print("unchecked: {d}\n", .{addUnchecked(250, extra)}); std.debug.print("checked: {d}\n", .{addChecked(250, extra)});}Run with -O debug and then -O fast. You’ll see something like:
== debugunchecked: 4thread 8252 panic: integer overflow== fastunchecked: 204thread 8265 panic: integer overflowIn both modes the unchecked add quietly gives a wrong (and different!) answer, and the checked one panics. The setting covers the block it’s written in, including blocks nested inside it, but not other functions it calls. The language reference on @setRuntimeSafety has the details.
Which one should you ship?
Section titled “Which one should you ship?”A reasonable default for most programs is safe. You get optimized code, and if a bug slips through, the program stops with a message and a line number instead of corrupting data or giving wrong answers. Users can report “it crashed at parser.zig line 80”, which is far easier to fix than “the totals are sometimes wrong”.
Choose fast when you’ve measured that the safety checks cost you real time in your program, and your tests are good. Choose small when size really matters, like a WebAssembly module loaded by a web page or firmware for a small device. And keep debug for development, where fast rebuilds and good error messages matter more than anything else.
The Optimization Mode section of the language reference sums up each mode in a few lines.
Practice
Section titled “Practice”1. Mode-dependent logging
Section titled “1. Mode-dependent logging”Write a program that prints verbose logging on in debug builds and verbose logging off in every other mode.
Hint: compare builtin.optimize with .debug. An if expression with else can choose the text.
Show solution
const std = @import("std");const builtin = @import("builtin");
pub fn main() void { const state = if (builtin.optimize == .debug) "on" else "off"; std.debug.print("verbose logging {s}\n", .{state});}Output:
verbose logging onzig run builds in debug, so you see “on”. With zig run main.zig -O safe it says “off”. Because builtin.optimize is known at compile time, the string that isn’t used doesn’t end up in the program.
2. Measure it yourself
Section titled “2. Measure it yourself”Build any small program of yours in all four modes and compare the file sizes. Then add -fstrip to the debug build and compare again.
Hint: zig build-exe main.zig -O small --name main-small gives each build its own file name.
Show solution
zig build-exe main.zig -O debug --name main-debugzig build-exe main.zig -O safe --name main-safezig build-exe main.zig -O fast --name main-fastzig build-exe main.zig -O small --name main-smallzig build-exe main.zig -O debug -fstrip --name main-debug-stripls -l main-*On Windows use dir main-* instead of ls -l. Expect debug to be the biggest and small the smallest, and the stripped debug file to be several times smaller than the normal one, because most of a debug file is debug information.
3. Keep one check
Section titled “3. Keep one check”You ship a program in fast, but one function, readHeader(len: usize, data: []const u8), takes an index from a file and reads data[len]. Make sure an out-of-bounds index still panics in the release build.
Hint: one line at the top of the function.
Show solution
fn readHeader(len: usize, data: []const u8) u8 { @setRuntimeSafety(true); return data[len];}With safety on in this function, a bad len gives a panic like index out of bounds: index 6, len 3 even when the rest of the program is built with -O fast. Without it, fast would read whatever memory lies past the end of data.
- Zig has four build modes:
debug(default),safe,fastandsmall. Pick one with-Oor-Doptimize. debugandsafekeep the safety checks;fastandsmallremove them, and a bug there becomes undefined behavior.- Release modes build much slower (they go through LLVM) and give much smaller, faster programs. Much of a big binary is debug info;
-fstripremoves it, andsmallstrips by default. - Leak reports from
init.gpa, error return traces and0xaafilling are development helpers that release modes drop. builtin.optimizetells your code the mode at compile time (builtin.modeis the deprecated name).@setRuntimeSafety(true/false)changes the checks for one block.- Ship
safeunless you’ve measured a reason to pickfastorsmall.
Next up: Zig Cross-Compilation, building Windows, macOS and ARM programs from the machine you’re on.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Optimization Mode: the official summary of the four modes.
- Zig language reference: @setRuntimeSafety: turning checks on and off for a block.
- Zig language reference: Illegal Behavior: every check that
debugandsafeperform. - Zig 0.17.0 release notes: Rename lang.OptimizeMode to lang.Optimize: the new mode names.