空合并运算符使用不当?
myFoo = myFoo ?? new Foo();
而不是
if (myFoo == null) myFoo = new Foo();
我认为第一行代码将始终执行分配的想法是否正确?另外,这是空合并运算符的错误使用吗?
myFoo = myFoo ?? new Foo();
instead of
if (myFoo == null) myFoo = new Foo();
Am I correct in thinking that the first line of code will always perform an assignment? Also, is this a bad use of the null-coalescing operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我比较了生成代码的 CIL(确保进行发布构建 - 在项目属性中选中优化代码,这对应于
csc.exe
上的/optimize
开关>)。这就是我得到的(使用 VS 2008 - 请注意Foo.MaybeFoo()
是一种有时返回null
,有时返回Foo
的方法)GetFooWithIf
:GetFooWithCoalescingOperator
:因此,除了额外的栈顶复制和弹出之外,其他都是相同的。如果这可以带来可衡量的性能差异,我会专门购买一顶帽子来吃它;因此,选择您认为可读性更好的那个。
(编辑)哦,JITter 可能足够聪明,甚至可以消除这种差异!
I compared the CIL of the generated code (making sure to do a Release build - with Optimize Code checked in the Project Properties, which corresponds to the
/optimize
switch oncsc.exe
). This is what I got (using VS 2008 - note thatFoo.MaybeFoo()
is a method that sometimes returnsnull
, sometimes aFoo
)GetFooWithIf
:GetFooWithCoalescingOperator
:Thus, the same except for an extra top-of-stack-duplication and pop. If this can be made to make a measurable performance difference, I will purchase a hat specifically for the purpose of eating it; therefore, go with the one that you feel offers better readability.
(edit) oh, and the JITter might be clever enough to get rid of even that difference!
我不认为这是对空合并运算符的错误使用。阅读代码时,尽量简短、简洁,代码的意图很明显。
使用这样的空合并运算符是正确的,您总是会得到一个赋值,但我不会担心这一点。 (如果事实证明它确实是性能问题,那么您已经知道如何解决它)。
I don't think this a bad use of the null-coalescing operator. When reading the code, it is as short and concise as possible, and the intent of the code is obvious.
It is correct that using the null-coalescing operator like this, you will always get an assignment, but I would not worry about that. (And if it really turns out to be a performance issue, you already know how to fix it).
你是正确的,第一行总是会进行分配。除非代码经常执行,否则我不会担心这一点。
You are correct in that the first line will always make an assignment. I would not worry about that unless the code is executed very often.