Hello! I'm new to Zig and have been pouring through this repo (which is really great btw! it's complicated enough to be interesting, but presented in a very reader-friendly way. thank you!)
I don't understand this piece of the code, and I'm hoping someone can explain it to me:
// all mutable state is in a single nested global
const State = struct {
...
audio: struct {
...
num_samples: u32 = 0,
// sample_buffer is separate in UndefinedData
} = .{},
...
};
var state: State = .{};
// keep the big undefined data out of the state struct, mixing initialized
// and uninitialized data bloats the executable size
const UndefinedData = struct {
tile_ram: [DisplayTilesY][DisplayTilesX]u8 = undefined,
color_ram: [DisplayTilesY][DisplayTilesX]u8 = undefined,
vertices: [MaxVertices]Vertex = undefined,
tile_pixels: [TileTextureHeight][TileTextureWidth]u8 = undefined,
color_palette: [256]u32 = undefined,
sample_buffer: [NumSamples]f32 = undefined,
};
var data: UndefinedData = .{};
Specifically, why is data
separate from state
? I tried making data
a field in state
to see what the difference would be:
const State = struct {
...
data: struct {
tile_ram: [DisplayTilesY][DisplayTilesX]u8 = undefined,
color_ram: [DisplayTilesY][DisplayTilesX]u8 = undefined,
vertices: [MaxVertices]Vertex = undefined,
tile_pixels: [TileTextureHeight][TileTextureWidth]u8 = undefined,
color_palette: [256]u32 = undefined,
sample_buffer: [NumSamples]f32 = undefined,
} = .{},
};
var state: State = .{};
$ zig version
0.10.0-dev.423+40c9ce2ca
# without any changes:
$ zig build -Drelease-small && du zig-out/bin/pacman.exe
122K zig-out/bin/pacman.exe
# moving data to be state.data, and making the necessary changes to the rest of the code:
$ zig build -Drelease-small && du zig-out/bin/pacman.exe
296K zig-out/bin/pacman.exe
keep the big undefined data out of the state struct, mixing initialized
and uninitialized data bloats the executable size
This is clearly true, but why? Why does mixing initialized and uninitialized data bloat the exe from 120K to 300K?
I noticed this pattern is not present in pacman.c, so it's something about Zig in particular?