Speed of boolean expression (C#) - c#

Hello I was thinking of what is better to write (in matter of speed and/or efficiency):
bool Method(...) { ... }
...
bool result = Method(...);
if (result == false)
{ ... }
// or
if (!result)
{ ... }
Or, alternatively...
if (result == true)
// or
if (result)
I'm asking because I use first one (result == false) but sometimes it gets very long, especially in condition ? expr : expr statements.

Personally, I cringe whenever I see something like result == false. It's a rather nasty misuse of the equality operator in my opinion, and totally unnecessary. While I'd imagine the compiler should turn the two expressions into the same byte code, you definitely want to be using !result. Indeed, it is not only the more direct and logical expression, but as you mention, makes the code a good deal shorter and more readable. I think the vast majority of C# coders would agree with me on this point.

Runtime speed is the same - both snippets compile to the same MSIL code representation.
Using (result == false) instead of (!result) feels kinda sloppy though.

There is no performance difference in runtime code. Most of the coding-guidelines in the companies i worked prefer !result.

I don't think there is any difference, and if there is you would probably have a hard time measuring it. Any difference is likely to be in the noise of the measurement.

You should definitely use the expression with the ! operator, not because it's faster but because it's safer.
If you accidentally use one equals sign instead of two, you assign the value to the variable instead of comparing the values:
if (result = false) {
For other data types the compiler can catch this, as an expression like (id = 42) has an integer value so it can't be used in the if statement, but an expression like (result = false) has a boolean value so the compiler has to accept it.
(An old C trick is to put the literal first so that it can't be an assignment, but that is less readable so the ! operator is a better alternative.)

I think there are three steps in this process. First, you believe that there should always be a comparison inside an if, so you write if(this.isMonkey == true) banana.eat();
Or, more realistically
if(SpeciesSupervisor.getInstance().findsSimilarTo(Monkey.class, 2) == true) {
String f = new PropertyBundle("bananarepo").getField("banana store");
EntitiyManager.find(Banana.class,f).getBananas().get(1).eat();
}
Then, you learn that it is fine to ask if(this.isMonkey) and that this formatting allows better reading as a sentence in this example ("if this is a monkey").
But at last, you get old and you learn that if(b) is not very readable, and that if(b==true) gives your poor brain some clue what is happening here, and that all these harsh claims of "misuse", "abuse", yada yada, are all a little overstated.
And as for the performance. In Java it would not make a shred of difference. I don't think .NET is so much worse. This is the easiest optimization a compiler could do, I would bet some money that the performance is the same.
Cheers,
Niko

Although I agree with #Noldorin that if(!result) is to be preferred, I find that if(result == false) and its ilk are very useful if you have to test a nullable bool, which most frequently happens in data access scenarios.
Edit: Here's a sample program that explains the different ways you can use the equality operator on a nullable bool.
class Program
{
static void Main(string[] args)
{
TestNullBool(true);
TestNullBool(false);
TestNullBool(null);
Console.ReadKey();
}
private static void TestNullBool(bool? result)
{
if (result == null)
{
Console.WriteLine("Result is null");
}
if (result == false)
{
Console.WriteLine("Result is false");
}
if (result == true)
{
Console.WriteLine("Result is true");
}
}
}
/* Output:
Result is true
Result is false
Result is null
*/

Related

bool? compare with bool vs GetValueOrDefault vs ?? operator

With numeric it is always same pretty:
if(a < 123) { ... } // disregards if `b` is `int?` or `int`
But with bool?:
bool? b = ...
if(b) { ... } // compiler error: can't convert bool? to bool.
There are following options:
if(b == false) { ... } // looks ugly, comparing bool? with bool
if(b.GetValueOrDefault()) { ... } // unclear when condition is true (one must know it's `false`)
if(b.GetValueOrDefault(true)) { ... } // required few seconds to understand inversion
I was curios whenever nullables (at least bool?) deserves this syntax to be used always:
if(b ?? false) { ... } // looks best to me
P.S.: this may looks like opinion-based question, but I didn't find similar to clear all my doubts alone... Perhaps some of those are best used in certain scenarios and I'd like to know in which ones.
The language designers had two choices, as far as allowing bool? to participate in control expressions of control statements requiring a bool:
Allow it, and make an arbitrary decision when it comes to null treatment
Disallow it, forcing you to make a decision each time it is relevant.
Note that the designers had much less of an issue with if(a < 123) statement, because "no" is a valid answer to questions "is null less than 123", "is null greater than 123", "is null equal to 123", and so on.
The if (b ?? false) and if (b ?? true) are very convenient constructs, which let you explain to the readers of your code and to the compiler in which way you wish to treat nulls stored in a bool? variable.
Every time I see someone using a nullable boolean bool?, I ask them why. Usually, the answer is -- "well, I'm not really sure". It is effectively creating a three state condition which in my opinion makes the code harder to read regardless. What does null mean, if it is always false then why bother with making it nullable in the first place?
But to answer your question more directly, I prefer the
if (b ?? false)
syntax over the
if (b.GetValueOrDefault())
Some years later and from personal experience I can tell that following syntax is clearly a winner:
if(b == false) { /* do something if false */ }
if(b == true) { /* do something if true */ }
if(b != false) { /* do something if NOT false, means true or null */ }
if(b != true) { /* do something if NOT true, means false or null */ }
What I thought as "ugly" turns out to be the easiest to understand.
== vs ??
Nullables are often results of linq queries and using ?? add unnecessary layer of complexity to understand the condition.
Compare
if(Items?.Any(o => o.IsSelected) == true)
vs
if(Items?.Any(o => o.IsSelected) ?? false)
The first one is much easier to read, it's a simple check if any item is selected.
When my (probably untrained?) mind reads the latter, I have to make a mental full stop at ??, do inversion and only then I understand when if block will be executed. With ?? I am likely to make a mistake when quickly looking throught the code written by someone else or even my own code given enough time has passed.

Use of uninitialized variable - the compiler is broken

Obviously the title is somewhat tongue in cheek, but I've checked and double checked and I can't see the error in my logic.
The compiler complains that variable parsed might not be initialized in the return statement. I don't agree. Which of us is wrong, and why?
public DateTime? Test(string nextDate)
{
DateTime parsed;
if (nextDate != "TBC" && !DateTime.TryParse(nextDate, out parsed))
{
throw new Exception();
}
if (nextDate == "TBC")
return null;
return parsed;
}
No, the compiler isn't broken at all.
The compiler isn't meant to be able to tell that
if (nextDate != "TBC")
and
if (nextDate == "TBC")
are mutually exclusive. It doesn't try to make any connection between the two conditions. So it can't tell that you'll definitely have called DateTime.TryParse(nextDate, out parsed) if you get as far as return parsed;.
Basically, the compiler follows relatively simple rules to determine definite assignment (and reachability). Simple rules are easy to reason about, easy to implement, and easy to code to.
Fortunately, you can make your code simpler and make it compile at the same time:
public DateTime? Test(string nextDate)
{
if (nextDate == "TBC")
{
return null;
}
DateTime parsed;
if (!DateTime.TryParse(nextDate, out parsed))
{
throw new Exception();
}
return parsed;
}
Now we're dealing with the "special case" of "TBD" in one place right at the start - and then we can ignore that special case for the rest of the code and call TryParse unconditionally, leaving parsed definitely-assigned.
if nextData == "TBC", your TryParse is not invoked, as the whole condition cannot be true anyway. Therefore parsed may not be initialized.
Both of you are right.
The logic for uninitialized variable checking looks at all possible control flow paths, without a deeper logic analysis. This part of the compiler does not care that nextDate == "TBC" and nextDate != "TBC" are never both true. So the compiler is right from his PoV.
You don't want to analyze the program logic too deeply in a compiler. You want simple, understandable rules. In complicated cases the compiler would need to basically run your whole program with all possible input values at compiletime to determine if a variable is initialized.
And you're right because you know that the conditions will work out, so that the use of the variable will never be reached if it wasn't initialized.
I'd rewrite your function like this:
public DateTime? Test(string nextDate)
{
DateTime parsed;
if (nextDate == "TBC" )
return null;
if(!DateTime.TryParse(nextDate, out parsed))
throw new Exception();
return parsed;
}
But since you're throwing an exception anyways, you might want to use Parse instead of TryParse.
as out is part of if statement you must need to inialize the value.
Because if satement go from left to right and in your case nextDate != "TBC" get validated first and than next statement get checked.
so this is like
if( fist check)
{
if(second check)
{
}
}

Conditional Statements difference

Is there any difference between below two statements
if (null != obj)
and
if (obj != null)
If both treated same which will be preferable?
The first is a Yoda condition. Use it you should not.
The difference here is the code generated. The two will not generate the exact same code, but in practice this will have no bearing on the results or performance of the two statements.
However, if you create your own types, and override the inequality operator, and do a poor job, then it will matter.
Consider this:
public class TestClass
{
...
public static bool operator !=(TestClass left, TestClass right)
{
return !left.Equals(right);
}
}
In this case, if the first argument to the operator is null, ie. if (null != obj), then it will crash with a NullReferenceException.
So to summarize:
The code generated is different
The performance and end results should be the same
Except when you have broken code in the type involved
Now, the reason I think you're asking is that you've seen code from C, which typically had code like this:
if (null == obj)
Note that I switched to equality check here. The reason is that a frequent bug in programs written with old C compilers (these days they tend to catch this problem) would be to switch it around and forget one of the equal characters, ie. this:
if (obj = null)
This assigns null to the variable instead of comparing it. The best way to combat this bug, back then, would be to switch it around, since you can't assign anything to null, it's not a variable. ie. this would fail to compile:
if (null = obj)
No, but the second way is more common and more readable (and more logical in my opinion)
No, there is not. It's exactly the same.
The style null == obj is sometimes just used to prevent the common typo obj = null to not accidently assign null to a variable, but with != there's absolutely no reason to do so.
In .NET it won't actually compile for the typo obj = null.
So the compiler prevents you from accidently doing it.
The Yoda condition comes originally from other languages, where this compiler feature is missing.
They are exactly the same.
Some people prefer to put the null as the first part of the expression to avoid errors like this
if (obj = null) // should be obj == null
But of course this doesn't apply to the != operator, so in your example it's just a difference of style.
First type of statement came from C/C++, where was possible to pass not boolean values to condition verification. E.g. anything not 0 was true, and zero was false:
if (5) { } // true
if (0) { } // false
Sometimes it created problems if you forgot to type one '=' char:
if (x = 5) { } // this was true always and changed x value
if (x == 5) { } // this was true, if x was equal to 5
So, Yoda syntax was used, to receive compiler error in case one '=' was missed:
if (5 = x) { } // this was generating compiler error for absent-minded programmers
if (5 == x) { } // this was true, if x was equal to 5
C# allow only boolean value in conditions, So
if (x = 5) { } // this won't compile
if (x == 5) { } // this is true, if x was equal to 5
What about boolean types?
if (y = true) { }
if (y == true) { }
Well, this is useless code, because you can just write if (y).
Conclusion: Yoda syntax is gone with C/C++ and you do not need to use it anymore.
The use of the first form
if (blah == obj)
stems from the days when compilers would not catch if (obj = blah) i.e. unintentional assignment, unless compile warning level was set to maximum

Difference between Forward and Reverse Comparison in C#

this is related to comparing values in C#.
basically by default, in C# till date i only used forward comparison as follows:
string value1 = "";
if (value1 == null)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
somewhere on Internet, i came across a link where it is said that while comparing values in C#, we should prefer Reverse Comparison as :
string value1 = "";
if (null == value1)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Now the problem is that is there any basic difference between the two ways of comparing values or not (i.e. both are same).
Looking for favorable replies.
Thanks
This is a hangover from languages where values are implicitly converted to a boolean type.
For the most part, anything that was non-null or non-0 would be treated as true, otherwise it was equivalent to false. This meant that any assignation of a constant would always be true.
This thing to remember here is that the assignment function returns the value assigned, much in the same way that 5 is the result of 2+3, myInt = 5 also returns 5.
Because of this, it was recommended that you check the variable against the constant. The null example is actually probably a bit contrived in this case, as it would, in most languages, return as false.
As an example:
if(i = 1)
{
printf("Always out\n");
}
else
{
printf("Never prints\n");
}
i is assigned the value of 1, which then returns the value of the assignment, 1, to the if statement. This is equivalent to true, and the if condition matches.
If you were to attempt to assign i to the constant 1, you wouldn't compile, and so it was recommended that you do things it that order (e.g. 1 == i).
This is not neccesary in C#, and further to your example, the recommended practice is to call if(String.IsNullOrEmpty(myStringValue)) { //.... }, as a string has... two ... default values from a semantic perspective.
Reverse comparison protects you from errors, when you use == (compare) instead of = (assign). But complier also warns you if you do this.

Do I understand this right? Comparing and assigning in one line of code?

Can someone tell me if I understand this right.
private void SetFontWeight(FontWeight weight)
{
boldButton.IsChecked = weight == FontWeights.Bold;
}
Like what is getting me is how everything is in one line. Like they are comparing and then assigning.
So is there like some order. Logically it seems like it would be like
boldButton.IsChecked = (weight == FontWeights.Bold);
Is that correct it first does comparison then assigns?
Or I guess the long way would be
if(weight == FontWeights.Bold)
{
boldButton.IsChecked = true;
}
else
{
boldButton.IsChecked = false;
}
I also find it kinda weird that they are comparing a struct(FontWeights) to a Class. I would have though it would be like
weight.IsBold == FontWeights.Bold
Yup, equality comparison has higher precedence than assignment. Assignment has basically the lowest precedence, so just about any other operators will be executed before assignment happens.
I'm pretty certain that it's equivalent to
boldButton.IsChecked = (weight == FontWeights.Bold);
This sort of thing was inherited from C (originally) and it has to use parentheses to force assignment first:
if ((x = getcode()) == BAD_CODE) ...
In terms of your misgivings over the comparison, this is just one of the wonderful things that become possible when you're allowed to override comparison operators.
In fact, some would argue that this example makes more sense since you shouldn't have to worry about whether it's the IsBold property that you have to compare. The clas should (and does) figure that out because you're comparing it in a "boldness" sort of way :-)
As far as my understanding is concerned, equality checks will be performed first. No matter you put brackets or not.
Sample code;
public boolean SampleFunction()
{
int a = 1;
int b = 2;
boolean c= false;
c= a==b;
return c;
}
This will first check if a is equal to b. So it will return boolean value and assign it to c.

Categories

Resources