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

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];
        }
    }
    

About Steven Engelhardt, CFA, AIF
Adjunct Professor of Software Engineering at DePaul University • Software Engineering, Data & Analytics in FinTech • Lives in Chicago, IL

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s