esb*_*enr 3 c# performance dictionary
我有一个缓存字典,并且 GetValueOrDefault(...) 非常适合这种情况。
var myThing = _cache.GetValueOrDefault("key", new Thing());
Run Code Online (Sandbox Code Playgroud)
我在文档中找不到默认值是否始终执行或仅在字典解析为空时执行。这很重要,因为在我的例子中,构建 Thing 会对性能产生重大影响(它是一个游戏),并且我只想在必要时构建它。
它总是会被执行。这就是将值传递给函数的语义:首先计算该值,然后传递该值。
相反,您可以使用其他重载GetValueOrDefault以及 null-coalesce ??:
var myThing = _cache.GetValueOrDefault("key") ?? new Thing();
Run Code Online (Sandbox Code Playgroud)
如果前半部分返回,则只会执行后半部分null。该类型显然需要可为空,因此要么是引用类型,要么是可为空值类型。