空合并运算符是否将结果缓存在C#中 [英] Does null coalescing operator cache the result in c#
问题描述
我知道做(myValue ?? new SomeClass())
与(myValue == null ? new SomeClass() : myValue)
但是出于好奇,当我调用一个函数时,性能会有所提高吗?
(getResult() ?? new SomeClass())
. getResult()
将执行两次吗?因为我只指定了一次方法调用,所以这似乎并不直观.
But out of curiosity, is there any performance benefit when I call a function, say
(getResult() ?? new SomeClass())
. Will getResult()
get executed twice? It seems unintuitive since I've specified the method call only once.
推荐答案
好吧,如果缓存"是指将其存储在临时变量中,那么可以.
Well, if by "caching" you mean storing it in a temporary variable, then yes.
此构造:
var result = (getResult() ?? new SomeClass());
可以被认为等同于此:
var <temp> = getResult();
if (<temp> == null)
<temp> = new SomeClass();
result = <temp>;
这还告诉您第二部分,如果第一个操作数不是null
,则根本不执行??
之后的操作数.
This also tells you that the second part, the operand after ??
isn't executed at all if the first operand is not null
.
因此,请回答您的具体问题:
So to answer your concrete questions:
- 每个操作数最多评估一次
- 仅当第一个操作数的值为
null
时,才对第二个操作数求值
- Each operand is evaluated at most once
- The second operand is only evaluated if the first one evaluates to
null
请注意,您可以将它们链接起来:
Note also that you can chain these:
var result = first() ?? second() ?? third() ?? fourth();
这将导致:
- 评估
first()
- 如果
first()
评估为null
,则评估second()
- 如果
second()
也评估为null
,则评估third()
- 如果以上所有条件均评估为
null
,则最终评估为fourth
- Evaluates
first()
- If
first()
evaluated tonull
, evaluatessecond()
- If
second()
evaluated tonull
as well, evaluatesthird()
- If all of the above evaluated to
null
, finally evaluatesfourth
结果是返回的第一个(非双关语)非空值.
The result is the first (no pun intended) non-null value returned.
使用新的?.
运算符,这种类型的代码将在新的C#中变得更好:
This type of code is about to get even better in new C# with the new ?.
operator:
var result = first?.second?.third;
这是基本的.
处理,即它将读取first
的second
成员,然后读取任何second
的third
成员,但是它将在第一个null
处停止,并且还将确保每个步骤仅评估一次:
This is basic .
handling, ie. it will read the second
member of first
, and then the third
member of whatever second
is, but it will stop at the first null
, and will also make sure to evaluate each step only once:
(obj as IDisposable)?.Dispose();
obj as IDisposable
只会计算一次.
TryGetObjectToSave()?.Save();
只会调用一次TryGetObjectToSave()
,并且如果返回某个内容,则将调用该内容上的Save()
方法.
Will only call TryGetObjectToSave()
once, and if it returns something, the Save()
method on that something will be called.
这篇关于空合并运算符是否将结果缓存在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!