Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization
Exploring the .NET CoreFX .net core csharp system.collections.immutable
Published: 2014-11-21
Exploring the .NET CoreFX Part 5: Keep Indexers Trivial to Allow JIT Optimization

This is part 5/17 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:
1
2
3
4
5
6
7
public T this[int index]
{
    get
    {
        return this.array[index];
    }
}

not:

1
2
3
4
5
6
7
8
9
public T this[int index]
{
    get
    {
        if (this.array == null)
            throw new NullReferenceException();
        return this.array[index];
    }
}