2013-08-29 143 views
14

MS分析儀推薦使用string.IsNullOrEmpty代替或者與出於性能原因爲什麼string.IsNullOrEmpty比比較快?

警告470 CA1820 null或空字符串comparising它的:Microsoft.Performance:替換調用「string.operator ==(字符串,字符串)」在...中調用'String.IsNullOrEmpty'。

這是爲什麼?不應該調用另一個函數並將它傳遞給某個對象,然後需要執行某種比較,這比執行比較本身更昂貴嗎?

實施例代碼

void Foo() 
{ // throws a warning 
    string x = "hello world"; 
    if (x == null || x == "") 
    { 
     Console.WriteLine("Empty"); 
    } 
} 

void Foo() 
{ // doesn't throw it 
    string x = "hello world"; 
    if (string.IsNullOrEmpty(x)) 
    { 
     Console.WriteLine("Empty"); 
    } 
} 
+2

顯示你比較'與String.IsNullOrEmpty'的代碼。 – MarcinJuraszek

+0

可能的答案http://stackoverflow.com/questions/10360370/why-is-string-isnullorempty-faster-than-string-length – Sachin

+0

http://www.dotnetperls.com/isnullorempty – Cynede

回答

12

MS分析推薦使用的,而不是要麼出於性能的考慮

警告470 CA1820 null或空字符串comparising它string.IsNullOrEmpty:Microsoft.Performance:更換調用「string.operator == (字符串,字符串)'在...中調用'String.IsNullOrEmpty'。

只是read the fine manual

的字符串進行比較,使用的Object.Equals空字符串。

...

使用String.length屬性或方法String.IsNullOrEmpty比較字符串比使用equals顯著更快。這是因爲Equals比IsNullOrEmpty執行的MSIL指令多得多,或執行指令的數量以檢索Length屬性值並將其與零比較。

...

要修復與該規則的衝突,改變使用length屬性和測試空字符串比較。如果以.NET Framework 2.0爲目標,請使用IsNullOrEmpty方法。

你的問題是沒有這麼多的null檢查,但對平等與空string實例,而不是測試(通過Equals),而不是檢查其Length

再次,從精細的手工:

public void EqualsTest() 
    { 
    // Violates rule: TestForEmptyStringsUsingStringLength. 
    if (s1 == "") 
    { 
     Console.WriteLine("s1 equals empty string."); 
    } 
    } 

    // Use for .NET Framework 1.0 and 1.1. 
    public void LengthTest() 
    { 
    // Satisfies rule: TestForEmptyStringsUsingStringLength. 
    if (s1 != null && s1.Length == 0) 
    { 
     Console.WriteLine("s1.Length == 0."); 
    } 
    } 
2

IsNullOrEmpty將被內聯,以便在調用方法的開銷將被避免。縱觀方法,飾有屬性

[__DynamicallyInvokable, TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] 

我還想補充一點,IsNullOrEmpty是從一個可讀性點更清晰,更具描述性的(在我看來)。

至於表現,如果您使用value.Length == 0;而不是x == "",我會很驚訝,如果有任何真正的差異。在內部,IsNullOrEmpty做到這一點

return value == null || value.Length == 0; 

if (x == null || x == "") 

讀取屬性需要比計算平等的開銷少。

+2

那麼通過調用String.IsNullOrEmpty(var)而不是(var == null || var == String.Empty)會獲得什麼性能? – sisve

+0

「更清晰,更具描述性?」 「str!= null && str!=」「''你能得到多少更清晰和更具描述性的? – Jon

+0

@Jon - 夠公平的,我添加了IMO。話雖如此,英文會比我的符號更清晰。 'IsNullOrEmpty'不言而喻,'str!= null && str!=「」'不是很好(雖然不是很難破解)恕我直言。 – keyboardP