Skip to content
Kavachकवच

Arenas

Also known as: arena allocator region bump allocation pool

● Advanced4 minBefore this: Automatic MemorySpec 6.3

An arena makes many short-lived values quickly from one block of memory, and frees them all at once at its end.

fn total_length(lines: [String]) -> Int {
    arena {
        const words = lines.flat_map(l => l.split(" "))
        words.sum(w => w.len())
    }
}

fn main() {
    print(total_length(["the quick fox", "jumps high"]))
}

The program ran and printed:

kavach run arena.kav

20
arena.kav: Kavach code, then what running it prints

All the words made inside the arena are freed together when it ends; only the block's value, the total, comes out. A value made inside can't be kept outside, and the compiler checks that:

fn main() {
    let kept: [String] = []
    arena {
        const words = "a b c".split(" ")
        kept = words
    }
    print(kept)
}

The compiler refused the program:

kavach run arena-escape.kav

error: this value was made inside the `arena` and can't be stored outside it: return it as the arena's value instead
arena-escape.kav: Kavach code, then what running it prints

Reach for an arena when measuring shows that making and freeing values is the slow part, not by default.