簡體   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