[英]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? 现在我的问题是:codesnippet#1相当于codesnippet#2吗?
Or does it take longer to run codesnippet #1? 或者运行codenippet#1需要更长的时间吗?
CodeSnippet #1: CodeSnippet#1:
var fatherName = father.Child.Father.Child.Father.Child.Name;
CodeSnippet #2: CodeSnippet#2:
var fatherName = father.Name;
The C# compiler will not optimize this, and will emit just all operations for calling the property getters. C#编译器不会对此进行优化,并且只会发出调用属性getter的所有操作。
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. 另一方面,JIT编译器可以通过内联这些方法调用来做得更好,但是无法进一步优化它,因为它不了解您的域。 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?
或者运行codenippet#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. 答案是“是”,运行第一个代码片段需要更长的时间,因为C#和JIT都无法优化它。
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
. 第一个代码片段会像预期的那样为您提供
NullReferenceException
,因为您没有为father.Child
分配任何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. 即使您确实将子项分配给
father.Child
属性,编译器也不能认为值总是保持这种状态,因此它无法优化第一个片段中的任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.