[ i.am.kon ]

[ i.am.kon ]

Index Manipulation

Let's say we wanted to track current index of some array, but we don't want to use branching.

Why? In some environments branching logic is slower than simple math operations. One example of environments is shaders code for computer graphics and it is more often unoptimized by a compiler. Also, I just like the way it looks.

Increment Index

public void MoveNext()
{
    ArrayIndex ++;
    ArrayIndex %= Array.Length;
}

Instead of checking if ArrayIndex is out of bounds, we simply do a modulo operation on the ArrayIndex each time we increment it and this will make sure ArrayIndex is always less than length of Array.

Decrement Index

public void MovePrevious()
{
    ArrayIndex --;
    ArrayIndex += Array.Length;
    ArrayIndex %= Array.Length; 
}

This one is a bit more complex because we need to make sure that ArrayIndex is never less than 0. We can do so by adding a length of the array before doing module operation.

Created by Konstantin Yavichev. Copyright 2025.