簡體   English   中英

與string.Empty(c#)相比的最佳性能

[英]Best performance comparing to string.Empty (c#)

兩者之間有什么區別嗎?

if(string.Empty.Equals(text))

if(text.Equals(string.Empty))

關於性能,意外行為或可讀性?

這些將具有相同的性能特征。

如果textnull ,則第二行拋出NullReferenceException

我個人發現:

if(text == string.Empty)

比您的選擇更具可讀性。

還有內置的:

if(string.IsNullOrEmpty(text))

對於.NET 4.0:

if(string.IsNullOrWhitespace(text))

我建議使用

if (string.IsNullOrEmpty(text))
{
}

因為我認為它更具可讀性,這是IMO中最重要的(實際上結果對於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,更易讀的解決方案IMO,看起來是最快的,所以請選擇;)

關於性能,他們將表現相同。 關於意外行為,如果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>

在這種情況下應該沒有性能差異。 這就像比較“x == y”和“y == x”。

我會說if (text == string.Empty)是最可讀的語法,但那只是我。

當然,您也可以使用if (string.IsNullOrEmpty(text)) { }string.IsNullOrWhiteSpace(text)

至於意外行為,這是一個非常簡單的字符串比較。 我無法想象你會如何從中獲得意想不到的行為。

暫無
暫無

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

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