Why is Zig (version 0.15.2) generating a `memcpy` in this code?

In my emulator I have this function:

    fn vram_read(self: *Self, addr: u16) u8 {
        return self.vram[self.mirror_vram_addr(addr)];
    }

vram is defined as vram: [2048]u8. In the profiler this simple function is taking 18% of the time because of a memcpy.

image

I asked codex where this memcpy was coming from and according to it, Zig generated code that was copying the 2KB array every time I read it from the array.

Codex suggested slicing the array (self.vram[0..][self.mirror_vram_addr(addr)] ) before reading from it to fix the issue. And, indeed that fixed the issue, the memcpy is entirely gone.
image

So why does Zig need a memcpy to read from the array?

The project was compiled with ReleaseFast.

1 Like

Sounds like a bug. I wonder if it’s fixed in either master or latest stable. seems like a pretty easy thing to pop into godbolt and test!

Relevant issue is likely https://github.com/ziglang/zig/issues/17580

It would probably be helpful if you could simplify your reproduction.