双问号('??')与是否在分配相同变量时 [英] Double question marks ('??') vs if when assigning same var

查看:62
本文介绍了双问号('??')与是否在分配相同变量时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅以下 SE答案.

写作时

A = A ?? B;

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

那是不是

if( null == A ) A = B;

在性能方面会更受欢迎吗?

would be preferred, performance wise?

还是我可以假设当同一对象位于 ?? 表示法中时,编译器会优化代码吗?

Or can I assume that the compiler optimizes the code when the same object is in the ?? notation?

推荐答案

尽管 ?? 的性能可以忽略不计,但有时副作用却可以忽略不计.请考虑以下程序.

Although performance for ?? is negligible, the side effect sometimes may not be negligible. Consider the following program.

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();
        }

    }
}

在我的PC上运行结果.

Run result on my PC.

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

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

Because there is an extra assignment using ??, and the performance of the assignment sometimes might not guaranteed. This might lead to a performance issue.

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

这篇关于双问号('??')与是否在分配相同变量时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆