tags:

views:

445

answers:

12

When using an if() statement is it better from a performance perspective to use == or !=

if(object==null)

or

if(object!=null)

Should the statement w/ the highest probability of success be first in the if() sequence?

+1  A: 

I don't think it makes any difference in regards to performance. I prefer to always test the positive condition first -- call it the optimistic approach. Doing this consistently makes my code easier to read (to me anyway).

Jamie Ide
+10  A: 

You shouldn't care.

If you're this concerned with efficiency you should be writing in a low level language. Not .Net.

Spencer Ruport
Oh don't start that argument. There are cases where C# beats C++ in performance due to JIT optimizations.
Will Eddins
+23  A: 

I very much doubt you'd ever notice any tangible difference; not least, there is brtrue and brfalse IL operators...

If you have performance issues, use a profiler, and look at real problems; this won't be it... it is premature optimisation.

Marc Gravell
Well said. Given the absence of any significant performance differences, the overriding issue should be code clarity.
Steven Sudit
It's not that performance problems exist, I am trying to be proactive about optimization where possible. This question is something that has occurred to me every now and then and I thought it would be helpful to get a collective answer.
ChrisP
Ok, well, now you have your answer.
Steven Sudit
+2  A: 

Should the statement w/ the highest probability of success be first in the if() sequence?

Generally yes. Using the && and || operators in a boolean expression will cause a short-circuit evaluation - if the evaluation of the first item makes the expression undeniably true, then none of the other items will be evaluated.

As to == vs. !=, even if there was a performance differential, it will never make a difference that you'll notice.

womp
+2  A: 

I'd say there would be no difference if the code is of the form:-

if(obj == null)
{
    // blah
}
else
{
    // blah
}

The compiler will translate your if statement into a branch, either brtrue or brfalse which have equivalent performance.

This sounds a little bit like you're micro-optimising; if you need to ask it's likely you're being overly zealous.

If you're really certain there will be a difference, try writing the code both ways and running stopwatches around the code, or use a profiler. Until you measure it it's still theory, and more often than not our instinct tends to be more off than we'd like to think on these things!

kronoz
A: 

There should be no performance difference between those.

Try to put cheap comparisons first when you chain them with && or ||. Because of short circuiting, your program won't evaluate the right side of the operator if the left side already determines the outcome (this comes in handy in other ways too).

Comparing references is much easier for a computer than manipulating strings for example. As you have already suggested, putting the case that occurs most frequently can be of benefit.

However, if at all possible, try to not mess up the readability while you're optimizing. Sacrificing readability for micro-optimization is hard to justify.

Example:

if (myString != null && myString.ToUpper() == "FOO")
{
    // This works because of short circuiting.
    // myString.ToUpper() will never be evaluated if myString is null.
}
Thorarin
+10  A: 

Hi there.

I just analysed the following code in .NET Reflector:

public static void Main(string[] args)
{
    object obj2 = null;
    if (obj2 == null)
    {
        Console.WriteLine("Is null");
    }
    if (obj2 != null)
    {
        Console.WriteLine("Is not null");
    }
}

and here is the resulting IL:

.method public hidebysig static void Main(string[] args) cil managed
{
    .custom instance void [mscorlib]System.STAThreadAttribute::.ctor()
    .maxstack 1
    .locals init (
        [0] object obj2)
    L_0000: ldnull 
    L_0001: stloc.0 
    L_0002: ldloc.0 
    L_0003: brtrue.s L_000f
    L_0005: ldstr "Is null"
    L_000a: call void [mscorlib]System.Console::WriteLine(string)
    L_000f: ldloc.0 
    L_0010: brfalse.s L_001c
    L_0012: ldstr "Is not null"
    L_0017: call void [mscorlib]System.Console::WriteLine(string)
    L_001c: ret 
}

From the above it seems that it makes no difference to performance which if() check you use. But, you could look at it this way - try using the if() check which is most likely to occur. So if the object is rarely going to be null at the point of the if check, then use if(object != null).+

Cheers. Jas.

Jason Evans
Ok, but the IL is never executed, so this doesn't tell us anything final. You'd have to analyze the machine code that's compiled JIT, and even then it would only tell you about a specific implementation. For all we know, it may be the same speed on 32-bit processors but different for 64-bit ones.
Steven Sudit
A: 

I'll start off with a warning against premature performance optimization. Focus on readability.

That being said I would examine the IL generated by these. That will tell you how many operations each requires.

I've never been system programmer so I've never really delved into CPU level performance tuning.

codeelegance
+2  A: 

Older processors that used static prediction, assumed the conditions to be false when filling their pipelines. I don't think this is relevant anymore.

Tamás Szelei
So if it's no longer relevant, why mention it?
John Saunders
Because he asked if there is any performance difference between using == and !=. This CAN be something, but unlikely.
Tamás Szelei
+3  A: 

The 9 nanoseconds you would have gained by using != instead of != were lost by asking this question. The choice of operators is not significant and these kinds of micro-optimizations should not factor into the design of your application.

However, order of if's is significant. C#'s && and || operators are short-circuited, meaning that if the first condition of an && is false, then C# won't evaluate the second condition -- likewise, if the first condition of an || is true, then there is no point evaluating the second condition.

You can use short-circuiting to your advantage. A rule of thumb is to structure conditions as follows:

  • When using &&, conditions most likely to fail should come first.
  • When using ||, conditions most likely to success should come second.
  • Conditions which take a very long time to execute should come last.

Using a trivial example:

if(existsInDatabase(username, password) && loginAttempts < 3) { ... }

existsInDatabase can take a long time to execute, it might require a trip to the database or a webservice. If loginAttempts >= 3, then we've wasted a trip to the database. We'll minimize our trips to the database by writing the code as follows:

if(loginAttempts < 3 && existsInDatabase(username, password)) { ... }

Little tweaks like this can sometimes make a huge difference, but you really need to profile before making these kinds of changes. If you spend 20 developer hours scouring your code and re-writing if statements for optimal execution, but you only speed up your application by .5 seconds, the net savings is -19.99 hours. Take this into consideration before micro-optimizing your application.

Juliet
A: 

NO!  

Simon_Weaver
A: 

When I start thinking about something like this in my code I recall the line from Robert Glass' book "Facts and Fallacies of Software Engineering"

"Efficiency stems more from good design than good coding."

Jeff did a post on this book listing the facts and fallaices: http://www.codinghorror.com/blog/archives/001083.html

the empirical programmer