Skip to content

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.

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.

zig run, zig build-exe and zig test take -O:

Terminal window
zig run main.zig # debug, the default
zig build-exe main.zig -O safe
zig build-exe main.zig -O fast
zig test main.zig -O small # tests can run in any mode too

In a project with a build.zig, the template’s standardOptimizeOption gives you -Doptimize (see Zig Build System):

Terminal window
zig build -Doptimize=safe
zig build run -Doptimize=fast
zig build --release=small # the same as -Doptimize=small

Plain 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=small

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):

Terminal window
zig run overflow.zig -O debug
zig run overflow.zig -O safe
zig run overflow.zig -O fast
zig run overflow.zig -O small

You’ll see something like this (the stack traces are trimmed):

== debug
thread 8097 panic: integer overflow
overflow.zig:7:7: 0x11e4321 in main (overflow.zig)
x += @intCast(args.len * 10);
^
== safe
thread 8102 panic: integer overflow
overflow.zig:7:7: 0x1027a61 in posixCallMainAndExit (overflow)
x += @intCast(args.len * 10);
^
== fast
x = 204
== small
x = 4

debug 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.

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. small strips it by default; the other modes keep it unless you ask.
  • debug builds in well under a second, release modes take much longer. On x86-64, debug uses 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 reason debug is the default: you rebuild constantly while working.
  • fast and safe are close. Stripped, fast comes 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.

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.

@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: debug
safety checks: true
debug build: printing extra details

Build 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:

== debug
unchecked: 4
thread 8252 panic: integer overflow
== fast
unchecked: 204
thread 8265 panic: integer overflow

In 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.

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.

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 on

zig 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.

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
Terminal window
zig build-exe main.zig -O debug --name main-debug
zig build-exe main.zig -O safe --name main-safe
zig build-exe main.zig -O fast --name main-fast
zig build-exe main.zig -O small --name main-small
zig build-exe main.zig -O debug -fstrip --name main-debug-strip
ls -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.

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, fast and small. Pick one with -O or -Doptimize.
  • debug and safe keep the safety checks; fast and small remove 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; -fstrip removes it, and small strips by default.
  • Leak reports from init.gpa, error return traces and 0xaa filling are development helpers that release modes drop.
  • builtin.optimize tells your code the mode at compile time (builtin.mode is the deprecated name).
  • @setRuntimeSafety(true/false) changes the checks for one block.
  • Ship safe unless you’ve measured a reason to pick fast or small.

Next up: Zig Cross-Compilation, building Windows, macOS and ARM programs from the machine you’re on.

Quick check

1. Which two modes keep runtime safety checks such as integer overflow detection?
2. A program prints a wrong number in fast but panics with "integer overflow" in debug. What's going on?
3. Why is debug the default mode?
4. In Zig 0.17 code, how do you check for a fast build?