liveBook · Manning

Comptime memorization

As explained in Systems Programming with Zig

Comptime memoization is the Zig compiler's caching of a compile-time function result for repeated calls with the same input.

When a comptime function cannot produce a different result for the same input, Zig memoizes it: once computed, that result is not recomputed. Repeated calls to countWordlist while parsing a wordlist therefore do not duplicate that compile-time work. section 4.1.3

Listing 4.4 Parsing the wordlist into an array
fn parseWordlist(
    comptime wordlist: []const u8, #1
) [countWordlist(wordlist)][4]u8 { #2
    var list: [countWordlist(wordlist)][4]u8 = undefined;
    var i: usize = 0;

    var word_iter = std.mem.tokenizeScalar(u8, wordlist, '\n');
    while (word_iter.next()) |word| : (i += 1) { #3
        if (word.len != 4) {
            @compileError(std.fmt.comptimePrint( #4
                "the word '{s}' is not four characters long.",
                .{word},
            ));
        }
        list[i] = word[0..4].*; #5
    }

    return list;
}

See countWordlist used to determine the array length and its allocation size in the wordlist parser. section 4.1.3

How Systems Programming with Zig covers it

How deep it goes
Explains the repeated-call guarantee and compiler caching, but stops short of describing cache internals.
Examples
Demonstrates repeated countWordlist calls while sizing and filling a parsed wordlist array.
What you can do after
Understand when repeated compile-time calls avoid recomputation while parsing a wordlist.
How it connects
Connects comptime memoization to compile-time functions and comptime parsing.

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.