Reuse variable or local variables?

Is there any difference that we know of regarding optimization if we reuse variables on the stack or make them local inside a block?

Little example:

var bb: u64 = undefined;
if (this) {
    bb = 42;
    // do things with bb
}
if (that) {
    bb = 43;
    // do things with bb
}

or

if (this) {
    var bb: u64 = 42;
    // do things with bb
}
if (that) {
    var bb: u64 = 43;
    // do things with bb
}

In my case there are like 5 of these variables I absolutely need. Wondering what the compiler makes of it in complicated cases.

1 Like

Compile it and find out!

But I would guess they would be identical.

3 Likes

AFAIK, currently, all local variables in a function get allocated to separate memory locations (regardless of block scope), Making your first example the more efficient use of memory, at the potential cost of subtle bugs to due to the reuse of the value. But this is a non-guaranteed happenstance of the current implementation.

You cannot depend on this behavior. No decision has been made and Zig does not yet have a specification. In the future, it may be decided to optimize stack frame layout and reuse locations that are out of scope. If that happens, then there would likely be no difference in the size of the two stack frames.

2 Likes

It’s worth noting that zig could leave this up to the optimiser, and zigs calculation of stack size doesn’t need to match what the optimiser achieves. It’s ok for zig to think the stack is a little larger than it needs to be.

This is a known issue with Zig:

Oho oho! That could explain some speedups and some slowdowns of some of my code which I was surprised about.