简体   繁体   中英

.NET 3.5/C#: Is there a performance difference between if() == and !=

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?

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.

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).+

You shouldn't care.

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

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

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.

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.

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!

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).

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.
}

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.

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM