繁体   English   中英

C#或JIT编译器是否足够智能来处理这个问题?

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

假设我们有以下型号:

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

以下实施:

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

现在我的问题是:codesnippet#1相当于codesnippet#2吗?

或者运行codenippet#1需要更长的时间吗?

CodeSnippet#1:

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

CodeSnippet#2:

var fatherName = father.Name;

C#编译器不会对此进行优化,并且只会发出调用属性getter的所有操作。

另一方面,JIT编译器可以通过内联这些方法调用来做得更好,但是无法进一步优化它,因为它不了解您的域。 优化这可能在理论上导致错误的结果,因为您的对象图可以构造如下:

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

或者运行codenippet#1需要更长的时间吗?

答案是“是”,运行第一个代码片段需要更长的时间,因为C#和JIT都无法优化它。

不,代码片段不相同。

第一个代码片段会像预期的那样为您提供NullReferenceException ,因为您没有为father.Child分配任何father.Child

即使您确实将子项分配给father.Child属性,编译器也不能认为值总是保持这种状态,因此它无法优化第一个片段中的任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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