是否有關於性能,意外的行爲或可讀性比較的String.Empty(C#)最佳性能
if(string.Empty.Equals(text))
和
if(text.Equals(string.Empty))
之間有什麼區別?
是否有關於性能,意外的行爲或可讀性比較的String.Empty(C#)最佳性能
if(string.Empty.Equals(text))
和
if(text.Equals(string.Empty))
之間有什麼區別?
這些將具有相同的性能特徵。
如果text
是null
,您的第二行將拋出NullReferenceException
。
我個人認爲:
if(text == string.Empty)
比任何你的選擇更具有可讀性。
並且還有內置的:
if(string.IsNullOrEmpty(text))
而對於.NET 4.0:
if(string.IsNullOrWhitespace(text))
應該有在這種情況下沒有性能上的差異。這就像比較「x == y」和「y == x」。
我想說if (text == string.Empty)
是最易讀的語法,但這只是我。
當然,您也可以使用if (string.IsNullOrEmpty(text)) { }
或string.IsNullOrWhiteSpace(text)
。
至於意外的行爲,這是一個非常簡單的字符串比較。我無法想象你會如何從中獲得意想不到的行爲。
我會建議使用
if (string.IsNullOrEmpty(text))
{
}
,因爲我認爲這是更具可讀性,這是國際海事組織最重要的這裏(實際上結果不會是null
值相同,但你的第二個版本,將引發此特定測試用例的例外情況)。
我不知道在生成的IL中是否有任何區別,但無論如何,這樣的微優化(如果有的話)顯然不會使您的應用程序更快。
編輯:
只是測試它,因爲我很好奇:
private static void Main(string[] args)
{
Stopwatch z1 = new Stopwatch();
Stopwatch z2 = new Stopwatch();
Stopwatch z3 = new Stopwatch();
int count = 100000000;
string text = "myTest";
z1.Start();
for (int i = 0; i < count; i++)
{
int tmp = 0;
if (string.Empty.Equals(text))
{
tmp++;
}
}
z1.Stop();
z2.Start();
for (int i = 0; i < count; i++)
{
int tmp = 0;
if (text.Equals(string.Empty))
{
tmp++;
}
}
z2.Stop();
z3.Start();
for (int i = 0; i < count; i++)
{
int tmp = 0;
if (string.IsNullOrEmpty(text))
{
tmp++;
}
}
z3.Stop();
Console.WriteLine(string.Format("Method 1: {0}", z1.ElapsedMilliseconds));
Console.WriteLine(string.Format("Method 2: {0}", z2.ElapsedMilliseconds));
Console.WriteLine(string.Format("Method 3: {0}", z3.ElapsedMilliseconds));
Console.ReadKey();
}
不知道測試是相關的,因爲測試微優化總是比它更復雜容貌,但在這裏一些結果:
Method 1: 611
Method 2: 615
Method 3: 336
方法1和2是相同的預期,並且方法3,更可讀解決方案國際海事組織,看起來像最快的一個,所以讓你的選擇;)
關於性能,他們將表現相同。關於意外行爲,如果text = null,則第二個可能會拋出NullReferenceException
。 if (!string.IsNullOrEmpty(text))
似乎更自然,雖然實現相同的事情(相同的性能,相同的結果),沒有意外的行爲和NRE的可能性。
它們是等效的。
第一種情況:
IL_0000: nop
IL_0001: ldsfld string [mscorlib]System.String::Empty
IL_0006: ldarg.0
IL_0007: callvirt instance bool [mscorlib]System.String::Equals(string)
IL_000c: ldc.i4.0
IL_000d: ceq
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: brtrue.s <target>
第二種情況:
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld string [mscorlib]System.String::Empty
IL_0007: callvirt instance bool [mscorlib]System.String::Equals(string)
IL_000c: ldc.i4.0
IL_000d: ceq
IL_000f: stloc.0
IL_0010: ldloc.0
IL_0011: brtrue.s <target>
幹了什麼你的測試說明了什麼?它真的很重要嗎?它很可能永遠不會是瓶頸(除非你正在排序/搜索或類似的情況下,你仍然需要首先配置文件,並且你會得到你的答案) –
'String.IsNullOrEmpty(text)'? – alex
'text.Length == 0' – ordag