Simple question (I think): Which of these pieces of code would execute faster in C#?
newSpeed = newSpeed > maxSpeed ? maxSpeed : newSpeed;
or
if (newSpeed > maxSpeed)
{
newSpeed = maxSpeed;
}
Simple question (I think): Which of these pieces of code would execute faster in 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.
E.g., when newSpeed <= maxSpeed
, no assignment is done, only a comparison.
In this instance the compiler takes the ternary line and creates an if statement... so it turns on to be the exact same thing.
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. 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.