Search code examples
c#optimization

Is the C# or JIT compiler smart enough to handle this?


Assuming we have the following model:

public class Father
{
    public Child Child { get; set; }
    public string Name { get; set; }

    public Father() { }
}

public class Child
{
    public Father Father;
    public string Name { get; set; }
}

And the following implementation:

var father = new Father();
father.Name = "Brad";
var child = new Child();
child.Father = father;
child.Name = "Brian";
father.Child = child;

Now my question: Is codesnippet #1 equivalent to codesnippet #2?

Or does it take longer to run codesnippet #1?

CodeSnippet #1:

var fatherName = father.Child.Father.Child.Father.Child.Name;

CodeSnippet #2:

var fatherName = father.Name;

Solution

  • The C# compiler will not optimize this, and will emit just all operations for calling the property getters.

    The JIT compiler on the other hand, might do a better job by inlining those method calls, but won't be able to optimize this any further, because it has no knowledge of your domain. Optimizing this could theorethically lead to wrong results, since your object graph could be constructed as follows:

    var father = new Father
    {
        Child = new Child
        {
            Father = new Father
            {
                Child = new Child
                {
                    Father = new Father { ... }
                }
            }
        };
    

    Or does it take longer to run codesnippet #1?

    The answer is "Yes", it would take longer to run the first code snippet, because neither C# nor the JIT can optimize this away.