This question already has answers here:
C# conditional AND (&&) OR (||) precedence
(6 answers)
Closed 1 year ago.
if (!d1.x0((long) d1.x1, out d2) || d1.x2 != 0 && d1.x2 != e1.x3 || d1.x4 != x4.None && d1.x4 != e1.x5 || d1.x6 != 0UL && (long) d1.x6 != e1.x6)
I spotted this in production C# code (var names replaced for anonymity) and I cannot understand if that statement can work in C#? or maybe other languages too?
I thought || needs to be explicitly grouped with a () if mixed with &&
If it compiles in C# it works. That doesn't mean it's correct. With your variable-name changes it is https://WorseThanFailure.com - worthy hard to read and reason about.
As you know, the language evaluates && and || operators, absent any parentheses, from left to right, with the same operator precedence. But conditionally! In a && b, if a is false b is not evaluated. A similar rule applies to ||.
So this very well could be correct. If it's in production code, and you're not chasing a bug in this part of the code you'd be wise not to touch it. If you do rewrite it, you must understand the desired application logic completely. And, you must inspect your rewrite very carefully and test the resulting code: this kind of logic is notoriously easy to screw up when you rewrite it.
C# got this && / || stuff from the C language. So did C++, Java, Javascript, and many other languages. It's incredibly useful. Time you spend becoming adept with it is time well spent.
I did the due-diligence to see if this has been asked before and didn't find anything identical but close, so here goes.
Say I have a chain of if-else-if statements.
foreach (value in valueList)
if (value == 120) {
w = true;
} else if (value == 140) {
x = true;
} else if (value == 160) {
y = true;
} else if (value == 180) {
z = true;
}
}
Is there any advantage of changing the else-if chain to ternary expressions such as:
foreach (value in valueList) {
w = (value == 120) ? true : false;
x = (value == 140) ? true : false;
y = (value == 160) ? true : false;
z = (value == 180) ? true : false;
}
My first inclination is no. Because of the for loop every assignment is made each time the loop happens. Whereas in the if-else-if chain, the assignment is made only once. But the comparisons are made more often (right?). Can anybody settle this for me?
I know a switch would easily defeat the both in terms of performance. Can I base this question on the assumption that using switch is not an option?
I guess another question inside this question would be what are the Big-O comparisons between the two?
Note that both solutions are very different. The first one only assigns true to one of those four variables while the other one will overwrite whatever value all four of them had before.
That being said, using the ternary operator in the second code is really bad. You can just assign the result of the comparison directly:
w = value == 120;
x = value == 140;
y = value == 160;
z = value == 180;
Taking aside the semantics, this will also make it likely a bit more performant than a if/else structure. You might think that just running a single comparison will make it faster, so the first solution should be better, but in fact, branching can be slow. And since comparison operations are actually really fast, just assigning the result of a comparison four times is likely “faster”.
Note that none of this will actually have any real performance impact. Both is very low-level and it’s very likely that you have something else in your application’s code that is way slower, being a likelier bottle neck. So I wouldn’t stress about using one or another way for performance here; just choose what is semantically correct and then use whatever solution makes the semantics as clear as possible.
I know a switch would easily defeat the both in terms of performance.
A switch statement gives you the same effect as a chain of ifs and elses, so there isn’t really a difference here.
I guess another question inside this question would be what are the Big-O comparisons between the two?
Both is linear, as you just loop through the list. Every other difference is constant, so it doesn’t matter in Big-O notation.
The two function entirely differently. Performance is irrelevant; they don't do the same thing.
The first snippet sets the appropriate variable to true if the condition is met, and does nothing if the corresponding condition isn't met, meaning it leaves the original value.
The second snippet assigns a value to each variable on each iteration.
So the first snippet is effectively asking, "is any value equal to this number" for each of the numbers, the second snippet is effectively asking, "is the last value equal to this number" for each of the numbers. I assume you intend the former, not the latter, so the latter is simply wrong.
Well, in the case of integers, I really like to use a switch when I have too many cases. #ima explains it in this answer. Otherwise, it only matters what looks better or more "readable"
However using a switch with strings is a totally different story as explained in this post.
1) I know how if…else if statements work, but in the next example both methods are identical as far as the resulting value is concerned. So does it matter which of the two methods I use or should I always go for one that is semantically closest to what the code is trying to do ( here I’m guessing that semantically the two methods are quite different )? So which method would you use and why?
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
else if (value >= bigNumber)
return bigNumberDescription;
else if (value >= smallNumber)
return smallNumberDescription;
else
return "";
}
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
else
return "";
}
2) I noticed losts of code uses the following format when writting if ... else if statements:
if ...
else if ...
else ...
But isn't ( at least conceptually ) more correct way:
if ...
else
if ...
else ...
You should probably use the first. It's more accepted, and more logical. (You don't care about anything afterwards if this condition is true... indicate that in your code.)
It's generally more accepted, and more compact and readable, to use the first way (else if). Python even has a specific keyword for it (elif).
I personally would use
protected string GetNumberDescription(int value)
{
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
return string.Empty;
}
It really all depends on what your function is doing. If its simple like this then keep it simple. If you might need to do something with the result before you return it then I'd use Egrunin's solution
protected string GetNumberDescription(int value)
{
string ret = "";
if (value >= veryBigNumber)
ret = veryBigNumberDescription;
else if (value >= bigNumber)
ret = bigNumberDescription;
else if (value >= smallNumber)
ret = smallNumberDescription;
return ret;
}
The question is already answered, but I added this because:
There are advantages to having a single exit from a function.
The same variable is being tested repeatedly, so the if/elseif is most appropriate.
Edited to add:
I'm usually a big fan of exiting a function early in cases like this:
if (conditionOne)
{
if (conditionTwo)
{
if (conditionThree)
{
interesting_stuff();
}
}
else
boring();
}
return;
I'm much happier seeing this:
if (!conditionOne)
return;
if (!conditionTwo)
{
boring();
return;
}
if (!conditionThree)
return;
interesting_stuff();
return;
But when there are exits at many different nesting levels, it's too easy to miss one as you're reading over the code.
Also, as mentioned in the comments: a single exit means only one place to put a breakpoint.
If the conditions are mutually exclusive then I think an else if pattern is best. It will be harder to accidentally break as the code evolves and becomes more complex, because your control flow more accurately represents the mutual exclusiveness of the logic.
Consider if someone re-factored your first example to be similar to egrunin's example such that there is only one return, but consider they forgot to add the "else" to each if:
protected string GetNumberDescription(int value)
{
string ret = "";
if (value >= veryBigNumber)
ret = veryBigNumberDescription;
if (value >= bigNumber)
ret = bigNumberDescription;
if (value >= smallNumber)
ret = smallNumberDescription;
// BUG: very big numbers still fall through to this last condition,
// because they meet all conditions
return ret;
}
They have just introduced a bug. They may not have realized that the returns were part of the logic being expressed. While the error is obvious here, in real life this code a couple years down the road could potentially become more complex, lengthy, and more difficult to read such that it's easier to make such a mistake.
Detecting Unexpected Bug
Additionally, if at least one condition must be met(i.e. should never return an empty string), then I'd throw an exception in the final else if you are assuming all cases should be handled. This would detect a bug in the code where the code fell through all the elses and did not find a matching condition. If you do not throw an exception, then the bug might cause strange behavior. How will the rest of the code handle the uninitialized empty string? Depends largely on the code at hand. The idea of throwing an exception is to cause a hard failure exactly where the bug is so that it can be easily identified and corrected, instead of allowing the application to continue running with an invalid return.
if (value >= smallNumber)
ret = smallNumberDescription;
else if(...)
ret = otherNumberDescription;
else
throw new InvalidOperationException($"No condition matched for value={value}");
return ret;
If paired with appropriate exception logging/notifications, then this would allow you to become aware of this bug and add a condition to handle unanticipated values. Not really necessary for very simple conditions, but very helpful in proactively finding and correcting bugs in this kind of code.
They are semantically identical. I doubt there is any difference in performance, so the choice is about style and readability. If you're curious, compile the above code into an assembly and use Reflector to see if there is any difference in the IL. My guess is there would be little difference if any.
It's mostly a matter of preference. when using return statements, you don't need the elses in my opinion, since it's clear that the function ends right there. It's all very situation and style dependent, so there is no clear 'best' way to do it.
I would suggest the former, as you are making a logical choice between four possibilities. You are grouping the decision in one if/else if block.
If you separate out the decisions like in your second function, they appear to not be connected at all. Clearly they are, as the value variable is repeated, but it might not necessarily be obvious.
Additionally, when you've got nothing to return, please return null, and not a blank string. In an application I maintain, it is still necessary to use if (value == null || value != "").
You want to use "else if" because that only will fire if the first "if" is not accepted. In your case the 3 if statements are okay, simply because if a latter "if" is correct, then the previous "if"s cannot be.
In a case where all of your if statements could be correct, you'd want to use else if.
For Example:
if (8<10) {
return 10;
}
if (8<9) {
return 9;
}
That's a very simplistic example, but you get the idea. You use "else if" when you want only one "if" statement to fire.
I would use the first option, as it shows in code the comparisons are "grouped" some. For 2 I think they end up in exactly the same IL code.
I always make sure the most common senario is first in the if..else statement, as that is best for performance.
The alternatives are pretty close semantically, so it doesn't matter that much. As suggested in some answers, putting the result in a string variable and return at the end might better represent what you are doing in the method.
Another alternative is to use the conditional operand, which gives you a less verbose code:
protected string GetNumberDescription(int value) {
return
value >= veryBigNumber ? veryBigNumberDescription :
value >= bigNumber ? bigNumberDescription :
value >= smallNumber ? smallNumberDescription :
String.Empty;
}
With the return statements, it really doesn't matter. I totally disagree with those who say the second is in any way worse, though. What makes it worse?
In response to your second question: you are quite right. In fact, not only are the two ways of formatting if/else if effectively the same; they actually are literally the same. C# does not enforce a particular formatting style, so these are all identical:
// This...
if (A())
return "Congrats!";
else if (B())
return "Not bad!";
else if (C())
return "Next time...";
else
return "Uh-oh.";
// ...is the same as this...
if (A())
return "Congrats!";
else
if (B())
return "Not bad!";
else
if (C())
return "Next time...";
else
return "Uh-oh.";
// ...which is the same as this...
if (A()) return "Congrats!"; else
if (B())
return "Not bad!";
else
{ if
(C())
return
"Next time...";else{
return "Oh-oh.";
}}
protected string GetNumberDescription(int value)
{
return new NumberDescriptor(value).toString();
}
All you need is to hide your logic.
Don't take this too serious, but...i would do it that way. I know, your question is not anserwed here, but there are already enough if/then/else examples in this topic.
1) The first one is more prevalent and in common practice. So it would be wise to stick to the standard practice.
2) Generally when we have more than one conditional statement, else if is used in the intermediate conditional outputs and else is used in the last conditional output. Moreover it might be more efficient as I believe it does not have to check the same condition everytime unlike the if-else-if-else... type.
Its more like a choice provided to you where you find your own out of many paths going to the same destination. But the choice that you hear or see often is the one that is popular because of experience of many users and experts.
I would say to use the first if the function is thought of as returning one of four possibilities, all of which are considered "successful". I would use the latter style if some returns denoted "failures". For example (toy example--throwing might be better for the error cases):
string get_suit_name(int suit)
{
string suit_names[4] = {"clubs", "diamonds", "hearts", "spades"};
if (0 > suit) /* Avoid LT sign */
return "Suit is improperly negative!";
if (suit >= 4)
return "Suit is too big!";
return suit_names[suit];
}
Well from my point of view it would be these priorities from highest to lowest.
Functionality / achieving the end goal
Reduction of cost in any scope/level
Readability
^^^^ note that many will dispute this on my list and call readability above reduction of cost, it really depends on your work envi. and the end goal but I find this the most common. But guess coming from a rookie that doesn't mean much huh :D
After that you it's pretty much peanuts. Same goes for ? : operator. If you are convinced it's more readable, go for it. Function wise it doesn't really matter. But if(){}else{} is significantly different from if(){}else if(){} So pick what's the optimum code (Highest wanted results minus unexpected results - 0.5* readability score ) pretty much what I'd go on.
Now seeing as the code does the same for you, a new attribute comes into play, will this code be edited at some later stage? And if so what would be best to go for then? Don't forget the future of the code, nor the comments, that a free bonus to pick along with it. You can even do both if you can't figure it out for the time and just comment the other but that does leave sloppy walls of text to be removed later on cleanup/release.
For the example provided, you don't need to worry about "if" statements if you're willing to sacrifice a ton of readability and possibly a little speed:
string [] descriptions = {"", smallNumberDescription, bigNumberDescription, veryBigNumberDescription};
protected string GetNumberDescription(int value)
{
int index = Convert.ToInt32(value >= smallNumber) + Convert.ToInt32(value >= bigNumber)
+ Convert.ToInt32(value >= veryBigNumber);
return descriptions[index];
}
In terms of performance, they may be the same depending on the compiler/interpreter. In my opinion the second one is better....much easier to debug.
Well, in your particular case, I would suggest this:
protected string GetNumberDescription(int value) {
if (value >= veryBigNumber)
return veryBigNumberDescription;
if (value >= bigNumber)
return bigNumberDescription;
if (value >= smallNumber)
return smallNumberDescription;
return "";
}
Since, you are returning from the function on any of the true condition, there is no need to use 'else if'. In your case, if any of the conditions become true, the code won't execute further.
Also, the last 'else' is not required, for the control will reach that point only when all the above conditions have been false.
It's all a matter of where you're using it, and how. The main motive is to maximize the readability of your code and make it as elegant and easy-to-understand as possible.
Many would prefer the first way since it indicates in your code that you don't care what happens as soon as a condition is satisfied.
I have to read a huge xml file which consists of over 3 million records and over 10 million nested elements.
Naturally I am using xmltextreader and have got my parsing time down to about 40 seconds from earlier 90 seconds using multiple optimization tricks and tips.
But I want to further save processing time as much as I can hence below question.
Quite a few elements are of type xs:boolean and the data provider always represents values as "true" or "false" - never "1" or "0".
For such cases my earliest code was:
if (xmlTextReader.Value == "true")
{
bool subtitled = true;
}
which i further optimized to:
if (string.Equals(xmlTextReader.Value, "true", StringComparison.OrdinalIgnoreCase))
{
bool subtitled = true;
}
I wanted to know if below would be fastest (because its either "true" or "false")?
if (xtr.value.length == 4)
{
bool subtitled = true;
}
Yes, it is faster, because you only compare exactly one value, namely the length of the string.
By comparing two strings with each other, you compare each and every character, as long as both characters are the same. So if you're finding a match for the string "true", you're going to do 4 comparisons before the predicate evaluates to true.
The only problem you have with this solution is, that if someday the value is going to change from true to let's say 1, you're going to run into a problem here.
Comparing length will be faster, but less readable. I wouldn't use it unless I profile the performance of the code and conclude that I need this optimization.
What about comparing the first character to "t"?
Should (maybe :) be faster than comparing the whole string..
Measuring the length would almost invariably be faster. That said, unless this is an experiment in micro-optimization, I'd just focus on making the code to be readable and convey the proper semantics.
You might also try something like that uses the following approach:
Boolean.TryParse(xmlTextReader.Value, out subtitled)
I know that has nothing to do with your question, but I figured I'd throw it out there anyway.
Cant you just write a unit test? Run each scenario for example 1000 times and compare the datetimes.
If you know it's either "true" or "false", the last snippet must be fastest.
Anyway, you can also write:
bool subtitled = (xtr.Value.length == 4);
That should be even faster.
Old question I know but the accepted answer is wrong, or at least, incorrect in it's explanation.
Comparing the lengths maybe be the slightest bit faster but only because string.Equals is likely doing some other comparisons before it too checks the lengths and decides that they are not equal strings.
So in practice this is an optimization of last resort.
Here you can find the source for .NET core string comparison.
String comparing and parsing is very slow in .Net, I'd recommend avoid intensive using string parsing/comparing in .Net.
If you're forced to do it -- use highly optimized unmanaged or unsafe code and use parallelism.
IMHO.
This question already has answers here:
Closed 13 years ago.
Most of us write conditionals like:
if (resultIndex == 0)
...but occaisionally I come across someone writing them like:
if (0 == resultIndex)
...and interestingly those people have been authors and seemingly pretty hot coders.
So why do some people choose the 'backwards' style? Is there some history behind it? Readabililty?
Duplicate: Why does one often see “null != variable” instead of “variable != null” in C#?.
It is a legacy from C, where a common bug would be to write
if (x = 0) {...}
If you taught yourself to write these tests the other way around, then the compiler would complain when you made the == typo, instead of silently adding a bug.
This has been asked numerous times before though I can't seem to find the Dup.
Essentially, this style is a hangover from C where a common mistake for
if (c == 5) //Comparison
was
if (c = 5) //Assignment
In the latter case, the compile rwould not complain so people wrote it like so to reduce the likelyhood of this happening
if (5 == c)
Because (in C, where most of those programmers probably learned; I can't remember if this holds in C#) if you leave off a = character in the 'regular' style, you'll overwrite the value you are trying to compare (and you'll be checking the boolean value of the assignment). If you do it in the 'backwards' style, you'll get a compiler error.
In C#, integer values are not implicitly casted to boolean, so if (a = 0) yields a compiler error and does not compile. Hence, this practice is outdated and totally unnecesary in C#.
The main reason behind this I believe is to prevent mistakes such as:
if (variable = 0)
Where you assign in the condition instead of comparing.
The reason this would fail the other way around is because you have a constant on your left side of the expression.
So if you were to mistakenly write:
if (0 = variable)
You would get a compilation error from trying to assign something to a constant.
In my opinion this has more in regard to programming style, but still might be a good tip for new programmers. But once you're a little more experienced, errors such as this don't happen and if they do you should be able to track them down pretty easily.