【发布时间】:2016-04-02 12:21:45
【问题描述】:
当使用?? null-coalescing 运算符实例化空对象时,与简单的if == null 语句相比,是否存在性能差异、额外循环等?将对象分配给自身有什么影响?
RedColorBrush = RedColorBrush ?? new SolidColorBrush(renderTarget, Color.Red);
对
if (RedColorBrush == null)
{
RedColorBrush = new SolidColorBrush(renderTarget, Color.Red);
}
【问题讨论】:
-
您在编译和检查生成的 IL 时发现了什么?
-
如果有任何差异(这是值得怀疑的),那么它应该是微不足道的,以至于您最关心的应该是可读性/可维护性,而不是可能的微优化。 (甚至可以在下一版本的编译器或 VM 中反转或消失)
-
我相信原因之一类似于三元运算符:对某些人来说更易读。
-
我在 ildasm 中打开了
.exe,不幸的是什么都看不懂),但我实际上同意@abelenky。
标签: c# if-statement null null-coalescing-operator