完整的 if/else 语句与条件运算符
大家好,
我有一个非常简单的问题不同的 if/else 语句。
除了编写更少的代码之外,与完整的 if/else 语句相比,使用条件运算符还有其他好处吗?
使用它时是否会提高性能、减少编译代码或其他任何对我有利的事情?
感谢您的帮助
马科
Possible Duplicates:
Benefits of using the conditional ?: (ternary) operator
Is the conditional operator slow?
Hi all,
I've got a pretty simple question regarding the different if/else statements.
Apart from writing less code, are there any other benefits for using the conditional operator as opposed to the full if/else statement?
Is there a performance increase, less compiled code, or anything else that would benefit me when using it?
Appreciate your help
Marko
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要专注于编写更少的代码...专注于最终变得更可读的代码。
有时
if
语句会更具可读性。有时条件运算符会更具可读性。我喜欢条件运算符,因为它可以用不同的方式计算一个逻辑值(例如,基于客户年龄的折扣)。不过,我不喜欢以复杂的方式使用它 - 在有意义的地方使用完整的 if/else 并没有什么问题。也值得记住空合并运算符...因此,
您可以使用
Again,它只在某些情况下有用 - 但在这些情况下它确实很方便。
Don't focus on writing less code... focus on the code you end up with being more readable.
Sometimes an
if
statement will be more readable. Sometimes the conditional operator will be more readable. I like the conditional operator in cases where it makes sense, in terms of different ways of calculating one logical value (e.g. a discount, based on the age of a customer). I don't like using it in convoluted ways though - there's nothing wrong with using a full if/else where it makes sense.It's worth remembering the null-coalescing operator too... so instead of:
you can use
Again, it's only useful in certain situations - but in those cases it's really handy.
在某些情况下,更好的可读性......我认为仅此而已。
不,没什么重要的。我认为无论如何它通常都会编译为相同的 IL...
所以最终,您应该只根据可读性进行选择。当编写完整的 if/else 更具可读性时,就这样做。如果它是一个非常简单且易于阅读的三元表达式,那就使用它。
Better readability, in some cases... I think that's all.
No, nothing significant. I think it will usually compile to the same IL anyway...
So eventually, you should only base your choice on readability. When it's more readable to write a full if/else, do it. If it's a very simple ternary expression that is easy to read, go for it.