简体   繁体   中英

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;

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.

No, the code snippets are not equivalent.

The first code snippet will give you a NullReferenceException just as expected, as you haven't assigned anything to father.Child .

Even if you did assign the child to the father.Child property, the compiler can't assume that the values will always stay that way, so it can't optimise away anything from the first snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM