Zig binary Size

Just in general, Zig programs are going to be somewhat larger than C programs. It doesn’t tend to be massive, and it isn’t inherent to the language: if you write Zig as much like C as possible, the difference vanishes.

Zig specializes more code. For instance, when you use a format string, Zig will produce a custom function at compile-time, which is safer than printf and usually faster: but it’s more code. If you have two kinds of hashmap, those will also be specialized; ReleaseSmall will try to consolidate that kind of thing sometimes, but that’s difficult and not always possible. C would handle that manually with somewhat terrifying void pointer arithmetic, or, just use a linked list.

Zig is still a ‘no runtime’ language, it’s suitable for microprocessors, embedded, skinny libraries and so on. To get a binary size which is competitive with C is possible, but you’ll need to program with that in mind.

Just as a point of comparison, I recently ported Lemon to Zig, in order to turn it into a parser generator for Zig code. One of the artifacts of that is just Lemon in Zig, which exhibits identical behavior insofar as I was able to make it do so. So it’s a like-for-like comparison, same program in two languages.

On my computer, lemon.c at -O3 is 130KiB, lemon.zig at -D=ReleaseFast is 541KiB. The latter embeds the template, contributing 37KiB to the weight, and is about 5% faster (the embedded template only accounts for about 1% of that, interestingly). A parser generator has a lot of print statements in it, so this comparison is guaranteed to favor C over Zig when it comes to binary size:

$ rg \\.print src/lemon.zig | wc -l
     178

Most programs aren’t like this. But they will usually be somewhat larger, for similar reasons.

@IntegratedQuantum already covered why that is, I just wanted to provide a high-level overview of what you can expect. If you really want to match C byte-for-byte, you can, but you’ll need to work at it.

Forgot to add: 252KiB in ReleaseSmall. But of course the C code is smaller using -Os as well. I did try that, and remember the ratio being roughly the same, but didn’t write the number down.

5 Likes