views:

334

answers:

8

I remember reading once that the order of the members of an evaluation is important. Such as

if (null == myClass)

is better (faster?) then

if (myClass == null)

is this the case? If so could someone explain how and why? If the answer requires a language then aim towards c#.
Thanks

+23  A: 

No, it is not faster. This is a relic from the old C days, it avoided doing bugs like

if(myClass = null) /* accident, sets myClass to null instead of comparing */

so you would always have the constant at the left:

if(null = myClass) /* throws an error at compile time */

However it makes no sense to do this in C# I believe..

driAn
for null, no, but for boolean values, yes! var = true evaluates to true, which is an acceptable expression for an if statement.
Nicholas Mancuso
@Nicholas Mancuso: true, but that's just another good reason for not doing explicit value checks for bools.
Brian Rasmussen
+3  A: 

It won't be faster unless your compiler is really dumb.

It does mean if you accidentally type = not == you'll get a compilation error, which is where I believe the idiom came from.

Personally, I'd say don't use assignments in conditions, and turn on the compiler warning that tells you when you do - then you can use the - to me - more natural

   if (myClass ==  null)
Paul
+1  A: 

No, that makes no difference. Putting the literal at the left hand side was an old C/C++ programming trick, avoiding pain when you accidentally typed = instead of ==. Since the literal isn't an lvalue, you'd get a compile error when you got it wrong.

Hans Passant
+1  A: 

As far as I know, the first notation is said better than the second one, not for performance purpose but for avoiding a common mistake in C and C children languages:

If you put the constant to the left of the == and the variable to the right, the compiler will detect if you typed = in place of ==.

Of course this does not work when you compare two variables.

mouviciel
This depends on whether you include C# and Java as "C children languages" - the problem doesn't exist in either of them (unless you're comparing booleans). Even in C, good compilers with appropriate warning levels will warn you.
Jon Skeet
+6  A: 

It's not faster since both sides of the == sign need to be evaluated. If you have more than one condition though then the short circuit rule apply.
The conditions are evaluated one after the other until a definite answer is reached and only till then.
So if you have

if ((a != null) && (someLongCheck()) ...

and a is null then someLongCheck() will not be called.

shoosh
A: 

The order of items in an individual evaluation, such as you ask, is irrelevant. The code still has to resolve both sides of the statement in order to determine equality or inequality.

The only opinion I've heard in favor of it that makes any kind of sense is for readability, in that the eye sees the expected value first. I personally find this style unreadable.

Tom Moseley
+5  A: 

Well, this completely depends on the language and the compiler. Using the C# compiler that comes with the framework, it doesn't matter, as the IL output is the same. Here is a sample routine:

static void Main(string[] args)
{
    // Create the instance.
    MyClass instance = new MyClass();

    if (null == instance)
    {
    }

    if (instance == null)
    {
    }
}

The IL for the first comparison is as follows:

L_0007: ldnull 
L_0008: ldloc.0 
L_0009: ceq 
L_000b: ldc.i4.0 
L_000c: ceq 
L_000e: stloc.1 
L_000f: ldloc.1 
L_0010: brtrue.s L_0014
L_0012: nop 
L_0013: nop

And the second:

L_0014: ldloc.0 
L_0015: ldnull 
L_0016: ceq 
L_0018: ldc.i4.0 
L_0019: ceq 
L_001b: stloc.1 
L_001c: ldloc.1 
L_001d: brtrue.s L_0021
L_001f: nop 
L_0020: nop

As you can see, the output is virtually identical except for the ordering of the items on the stack. The operations are the same.

As mentioned before, it is a relic from the old C days where anything with a 0 value evaluated to false, and if you missed an equal sign, the assignment was evaluated as the conditional.

You don't have to worry about that in .NET, as conditionals will only accept boolean values, but if you are comparing against true/false, it might still be better coding practice to put the literal value first, so as not to accidentally evaluate an assignment.

casperOne
nice use of clarifying IL :)
Mark Maxham
Tip: To compare IL you really need to compile in release mode. In this case, there's no significant difference, but otherwise use release mode when comparing generated code.
Brian Rasmussen
+4  A: 

I remember reading once that the order of the members of an evaluation is important.

In addition to what others have said, I think you remember reading the order of statements in an if statement can affect its evaluation.

Since the && and || operators are overloaded, you can tweak yoru code for a little better performance using the following guidelines:

  • When using &&, order your conditions so the condition most likely to fail comes first.
  • When using ||, order your conditions so the condition most likely to succeed comes first.

Lets say your business requires you to generate TPS Reports each Monday, you might write code like this:

Sample #1:

if (DateTime.Today.DayOfWeek == DayOfWeek.Monday
    && !Database.TpsReportsExist())
{
    // create TpsReports
}

Sample #2:

if (!Database.TpsReportsExist()
    && DateTime.Today.DayOfWeek == DayOfWeek.Monday)
{
    // create TpsReports
}

Samples 1 and 2 are equivalent, but Sample #2 executes a query against the database no matter what day of week it is. Sample #1 avoids the unnecessary database hit, so we save a few CPU cycles and runtime.

The sample above is trivial, but it can make a huge difference in performance if you were executing this kind of code in a tight loop.

Juliet