# Optimized runtime known array indexing

**URL:** <https://ziggit.dev/t/optimized-runtime-known-array-indexing/8225>\
**Category:** Help\
**Tags:** simd, vectors\
**Created:** [January 28, 2025, 12:11pm UTC](https://ziggit.dev/t/optimized-runtime-known-array-indexing/8225 "2025-01-28T12:11:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jopo666](https://ziggit.dev/user_avatar/ziggit.dev/jopo666/32/4401_2.png) [@jopo666](https://ziggit.dev/u/jopo666)\
**Post date:** [January 28, 2025, 12:11pm UTC](https://ziggit.dev/t/optimized-runtime-known-array-indexing/8225/1 "2025-01-28T12:11:23Z")

</div>

I’m attempting to optimize the following function.

```zig
/// Swap each byte in data based on the passed lookup table.
pub fn translate(data: []u8, lut: [256]u8) void {
    assert(data.len > 0);
    assert(data.len % 256 == 0);
    for (data) |*px| {
        px.* = lut[px.*];
    }
}`

```

However I’m having trouble figuring out a way to index into the `lut` array  
efficiently? `@shuffle` can be used only when the `mask` is known at compile  
time and this would be a lot faster than the implementation above.

```zig
/// Swap each byte in data based on the passed lookup table.
pub fn translate(data: []u8, lut: [256]u8) void {
    assert(data.len > 0);
    assert(data.len % 256 == 0);
    const lut_vec: @Vector(256, u8) = lut;
    var cursor = data[0..];
    while (true) {
        const chunk: @Vector(256, u8) = cursor[0..256].*;
        // this will fail with: `note: shuffle mask must be comptime-known`
        const result: [256]u8 = @shuffle(u8, lut, undefined, chunk);
        cursor[0..256].* = result;
        cursor = cursor[256..];
        if (cursor.len == 0) break;
    }
}`

```

---

<div class="post-metadata">

**Author:** ![IntegratedQuantum](https://ziggit.dev/user_avatar/ziggit.dev/integratedquantum/32/782_2.png) [@IntegratedQuantum](https://ziggit.dev/u/IntegratedQuantum)\
**Post date:** [January 28, 2025, 5:27pm UTC](https://ziggit.dev/t/optimized-runtime-known-array-indexing/8225/2 "2025-01-28T17:27:57Z")

</div>

There is an accepted proposal for this: [Indexing arrays with vectors (gather) · Issue #12815 · ziglang/zig · GitHub](https://github.com/ziglang/zig/issues/12815)  
Andrew also posted a workaround there (which might not be that efficient though)

---

<div class="post-metadata">

**Author:** ![LucasSantos91](https://ziggit.dev/user_avatar/ziggit.dev/lucassantos91/32/440_2.png) [@LucasSantos91](https://ziggit.dev/u/LucasSantos91)\
**Post date:** [January 28, 2025, 6:31pm UTC](https://ziggit.dev/t/optimized-runtime-known-array-indexing/8225/3 "2025-01-28T18:31:43Z")

</div>

What assembly are you getting with the naive version?  
With PRO slotted for removal, you should probably pass the lut by const pointer, and mark it as `noalias`. See what assembly you get out of this and work from that.
