簡體   English   中英

創建變量或調用方法幾次 - 哪個更好?

[英]Create variable or call method few times - What's better?

我想知道幾次創建新的變量或調用方法。 整體性能和GC清潔有什么好處? 看一看:

public static string GetValue(RegistryKey key, string value)
{
    if (key.GetValue(value) == null)
        return null;
    string newValue = key.GetValue(value).ToString();
    if (String.IsNullOrWhiteSpace(newValue))
        return null;
    return newValue.ToLower();
}

如何清除此代碼?

通常,當您需要多次使用方法調用的結果時,應首先將其分配給局部變量。 局部變量只需要你的方法的堆棧幀大幾個字節(對於64位的對象變量為8個字節),並且在方法返回時會自動清除 - 它對GC沒有影響。

另一方面,重復的方法調用將需要再次執行其所有邏輯,從而導致所需堆棧幀的分配以及可能的對象實例化。 在您的情況下, RegistryKey.GetValue使情況更糟,因為它需要訪問Windows注冊表,使其比本地變量訪問慢幾個數量級。 此外,您可能面臨兩種調用返回不同值的競爭條件。

public static string GetValue(RegistryKey key, string name)
{
    object value = key.GetValue(name);
    if (value == null)
        return null;
    string valueStr = value.ToString()
    if (String.IsNullOrWhiteSpace(valueStr))
        return null;
    return valueStr.ToLower();
}

請注意,此問題將在C#6中得到很大程度的解決,您可以使用空條件運算符:

public static string GetValue(RegistryKey key, string name)
{
    string value = key.GetValue(name)?.ToString();
    if (String.IsNullOrWhiteSpace(value))
        return null;
    return value.ToLower();
}

創建一個局部變量並調用該方法一次。 本地方法調用(通常很小)開銷。 如果您使用遠程方法調用,差異將更加明顯。

用? 如你所見,運算符使其更具可讀性和更好的性能

public static string GetValue(RegistryKey key, string value)
{
    string valueStr=(string)key.GetValue(value);
    return string.IsNullOrWhiteSpace(valueStr)?null:valueStr.ToLower();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM