双重问号('??')与分配相同的var时的比较

问题描述 投票:14回答:5

参考以下SE answer

写作时

A = A ?? B;

它是一样的

if( null != A )
    A = A;
else
    A = B;

这是否意味着

if( null == A ) A = B;

性能明智吗?

或者我可以假设编译器在??表示法中使用相同的对象时优化代码?

c# compiler-optimization null-coalescing-operator
5个回答
2
投票

虽然??的表现可以忽略不计,但副作用有时可能不容忽视。考虑以下程序。

using System;
using System.Diagnostics;
using System.Threading;

namespace TestProject
{
    class Program
    {
        private string str = "xxxxxxxxxxxxxxx";
        public string Str
        {
            get
            {
                return str;
            }
            set
            {
                if (str != value)
                {
                    str = value;
                }
                // Do some work which take 1 second
                Thread.Sleep(1000);
            }
        }

        static void Main(string[] args)
        {
            var p = new Program();

            var iterations = 10;

            var sw = new Stopwatch();
            for (int i = 0; i < iterations; i++)
            {
                if (i == 1) sw.Start();
                if (p.Str == null)
                {
                    p.Str = "yyyy";
                }
            }
            sw.Stop();
            var first = sw.Elapsed;

            sw.Reset();
            for (int i = 0; i < iterations; i++)
            {
                if (i == 1) sw.Start();
                p.Str = p.Str ?? "yyyy";
            }
            sw.Stop();
            var second = sw.Elapsed;

            Console.WriteLine(first);
            Console.WriteLine(second);

            Console.Write("Ratio: ");
            Console.WriteLine(second.TotalMilliseconds / first.TotalMilliseconds);
            Console.ReadLine();
        }

    }
}

在我的电脑上运行结果。

00:00:00.0000015
00:00:08.9995480
Ratio: 5999698.66666667

因为使用??进行了额外的分配,并且有时可能无法保证分配的性能。这可能会导致性能问题。

我宁愿使用if( null == A ) A = B;而不是A = A ?? B;


12
投票

不要担心性能,它可以忽略不计。

如果您对此感到好奇,请编写一些代码来使用Stopwatch测试性能并查看。我怀疑你需要做几百万次迭代才能开始看到差异。

你也可以永远不会假设事情的实施,他们将来可能会改变 - 使你的假设无效。

我的假设是性能差异可能非常非常小。为了便于阅读,我会选择空合并操作符,它很好并且很简单,并且很好地传达了这一点。我有时会进行延迟加载检查:

_lazyItem = _lazyItem ?? new LazyItem();

3
投票

我的建议是检查IL(中间语言)并比较不同的结果。然后,您可以准确地看到每个归结为什么,并决定什么是更优化。但正如亚当在评论中所说的那样,你最有可能把注意力集中在可读性/可维护性而非性能上。

编辑:您可以使用Visual Studio附带的ILDASM.exe查看IL并打开已编译的程序集。


3
投票

我只是在C#中尝试过这个 - 很快,所以我的方法可能会出错。我使用以下代码并确定第二种方法比第一种方法长约1.75倍。 @Lockszmith:在下面的编辑之后,比率为1.115,有利于第一次实施

即使他们花了相同的时间,我也会亲自使用内置的语言结构,因为它可以更清楚地表达您对未来可能具有更多内置优化的编译器的意图。

@Lockszmith:我编辑了代码以反映评论中的建议

var A = new object();
var B = new object();

var iterations = 1000000000;

var sw = new Stopwatch();
for (int i = 0; i < iterations; i++)
{   
    if( i == 1 ) sw.Start();
    if (A == null)
    {
        A = B;
    }
}
sw.Stop();
var first = sw.Elapsed;

sw.Reset();
for (int i = 0; i < iterations; i++)
{
    if( i == 1 ) sw.Start();
    A = A ?? B;
}
sw.Stop();
var second = sw.Elapsed;

first.Dump();
second.Dump();

(first.TotalMilliseconds / second.TotalMilliseconds).Dump("Ratio");

1
投票

是,有一点不同。

使用针对Visual Studio 2017 15.9.8.NET Framework 4.6.1。考虑下面的示例。

static void Main(string[] args)
{
    // Make sure our null value is not optimized away by the compiler!
    var s = args.Length > 100 ? args[100] : null;
    var foo = string.Empty;
    var bar = string.Empty;

    foo = s ?? "foo";
    bar = s != null ? s : "baz";

    // Do not optimize away our stuff above!
    Console.WriteLine($"{foo} {bar}");
}

使用ILDasm很明显,编译器不会平等对待这些语句。

??运营商:

IL_001c:  dup
IL_001d:  brtrue.s   IL_0025
IL_001f:  pop
IL_0020:  ldstr      "foo"
IL_0025:  ldloc.0

条件空检查:

IL_0026:  brtrue.s   IL_002f
IL_0028:  ldstr      "baz"
IL_002d:  br.s       IL_0030
IL_002f:  ldloc.0

显然,??运算符意味着堆栈值的重复(应该是s变量吗?)。我进行了一次简单的测试(多次)以了解两者中的哪一个更快。在string上运行,在这台特定的机器上运行,我得到了这些平均数:

?? operator took:           583 ms
null-check condition took: 1045 ms

基准样本代码:

static void Main(string[] args)
{
    const int loopCount = 1000000000;
    var s = args.Length > 1 ? args[1] : null; // Compiler knows 's' can be null
    int sum = 0;

    var watch = new System.Diagnostics.Stopwatch();
    watch.Start();

    for (int i = 0; i < loopCount; i++)
    {
        sum += (s ?? "o").Length;
    }

    watch.Stop();

    Console.WriteLine($"?? operator took {watch.ElapsedMilliseconds} ms");

    sum = 0;

    watch.Restart();

    for (int i = 0; i < loopCount; i++)
    {
        sum += (s != null ? s : "o").Length;
    }

    watch.Stop();

    Console.WriteLine($"null-check condition took {watch.ElapsedMilliseconds} ms");
}

所以答案是肯定的,存在差异。

PS。 StackOverflow应该在同一句话中自动警告提及“性能”和“可忽略”的帖子。只有原始海报才能确定时间单位是否可以忽略不计。

© www.soinside.com 2019 - 2024. All rights reserved.