简体   繁体   English

更快些:if语句或条件运算符? (C#)

[英]What's faster: if statement or conditional operator? (C#)

Simple question (I think): Which of these pieces of code would execute faster in C#? 一个简单的问题(我认为):在C#中,以下哪段代码可以更快地执行?

newSpeed = newSpeed > maxSpeed ? maxSpeed : newSpeed;

or 要么

if (newSpeed > maxSpeed)
{
    newSpeed = maxSpeed;
}

I am guessing the second would be faster, in some cases, as it does not always do an assignment, whereas the first always does an assignment. 我猜第二个在某些情况下会更快,因为它并不总是执行任务,而第一个总是执行任务。

Eg, when newSpeed <= maxSpeed , no assignment is done, only a comparison. 例如,当newSpeed <= maxSpeed ,不进行分配,仅进行比较。

In this instance the compiler takes the ternary line and creates an if statement... so it turns on to be the exact same thing. 在这种情况下,编译器将采用三进制行并创建一条if语句...,因此它变成完全相同的东西。

Link: http://www.dotnetperls.com/ternary 链接: http//www.dotnetperls.com/ternary

You need as justnS said, ternary operators will be converted to if statements, while compiling, but if your using a ternary operator, you will need an if and an else part, while the if statement has no else. 正如justnS所说,您需要在编译时将三元运算符转换为if语句,但是如果您使用三元运算符,则将需要if和else部分,而if语句则没有else。 So maybe there will be a noticeable difference, if you run the code a few million or billion times. 因此,如果将代码运行几百万或十亿次,也许会有明显的不同。 But it does not matter, if your building a normal program. 但这并不重要,如果您构建的是正常程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM