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");
}
}
顯示你比較'與String.IsNullOrEmpty'的代碼。 – MarcinJuraszek
可能的答案http://stackoverflow.com/questions/10360370/why-is-string-isnullorempty-faster-than-string-length – Sachin
http://www.dotnetperls.com/isnullorempty – Cynede