Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization

Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization

Page content

This is part 5 of my Exploring the .NET CoreFX Series.

This is a simple recommendation based on observations from System.Collections.Immutable.

Recommendations

  1. Keep the implementation of an indexer as trivial as possible to allow the JIT optimization of removing array bounds checking to work. For example, don’t check if a member variable is null; just use it and allow the NullReferenceException to happen naturally. In other words, use:
public T this[int index]
{
    get
    {
        return this.array[index];
    }
}

not:

public T this[int index]
{
    get
    {
        if (this.array == null)
            throw new NullReferenceException();
        return this.array[index];
    }
}