2

I'm wondering which of the two options below is the most efficient in term of speed. There is probably just a really small difference between them (or no difference at all ?) but since I'm using that snippet of code 30 times a day, I would like to know what's the "best practice" here :)

Option 1 :

if (sender != null)
   LabelSave.Text = "Saved";
else
   LabelSave.Text = "Auto-Saved"; 

Option 2 :

if (sender == null)
    LabelSave.Text = "Auto-Saved";
else
    LabelSave.Text = "Saved";

Please don't take in consideration the value of the "sender" variable, the real question here is "what is the fastest operator between "!=" and "==" in c# ?"

abatishchev
  • 98,240
  • 88
  • 296
  • 433
sphax
  • 55
  • 1
  • 7
  • 4
    You've written the code both ways. If you want to know which is faster, take the next step: **run it both ways**. Then you'll know which is faster. – Eric Lippert Mar 24 '14 at 03:55
  • 1
    Did you run into any problems with that code? Did you see any performance issues with that particular line? There might be a minimal difference, but in real world you should not care about, at alll. – MarcinJuraszek Mar 24 '14 at 03:55
  • 9
    Also keep in mind that "30 times a day" is essentially "zero times a day". Your machine can do four billion operations per second. If you're not doing it several trillion times per day, don't worry about how fast it is. – Eric Lippert Mar 24 '14 at 03:56
  • 1
    Can I offer a 3rd option? LabelSave.Text = (sender == null) ? "Auto-Saved" : "Saved"; – failedprogramming Mar 24 '14 at 03:59
  • Performance doesn't matter here. Readability does. – abatishchev Mar 24 '14 at 04:01
  • 1
    @Eric/Marcin : Thanks Eric for your advice :) But even if the difference is meaningless compare to the billion operations done per day, do you know if, on a binary level, the operator "==" require more work for the processor compare to the "!=" ? – sphax Mar 24 '14 at 04:08
  • @abatishchev : good point abatishchev, but in this case, the readability is the same in both cases, no ? :) – sphax Mar 24 '14 at 04:10
  • 2
    @sphax: There are few if any operations in a computer that are faster than "is this zero?" and "is this not zero?" The expense is not in the computation; **the expense is whether or not the branch predictor on the chip guesses wrong**. If you want an answer to the question of which is faster from an *a priori* perspective rather than measuring it and finding out, you're going to have to study the chip architecture at quite a deep level. – Eric Lippert Mar 24 '14 at 04:10
  • @sphax Depends on the processor. Some are good at branch predictions, some not so much. Line caching is performed differently. Instruction sets are different. Maybe both kind of braches are both turned into a JNE (Jump if Not Equal) instruction anyway. You're asking things that are very dependent on other information. – itsme86 Mar 24 '14 at 04:11
  • 1
    Be grateful eric is commenting, value information is given here. One friend once told me, If you wish your code to be that fast, do it in C, and no, you will not see any difference in how you implement this comparison. The things that should concern regarding to performance, are: DB, File-system writing, etc.. not memory based operations like this one! – ilansch Mar 24 '14 at 04:12
  • 3
    More generally: you are going down the path of nano-scale optimizations. This is a bad path to be on. The way to get a high performance application is: set a performance goal, carefully measure your performance against the goal, when you fail to meet your goal use a profiler to find the slowest thing, fix that, and repeat. Nano-optimizing individual statements is like trying to weed a garden full of kudzu by trimming the edges of a couple leaves with nail scissors. – Eric Lippert Mar 24 '14 at 04:14
  • 1
    Another way to look at this question is: displaying the text even *once* will be literally *millions* of times more expensive than any possible gain you make by making the "right" choice of operator. The way to get good performance is to concentrate on the expensive things; you're concentrating on literally the cheapest possible thing. – Eric Lippert Mar 24 '14 at 04:17
  • @All : Thanks a lot guys for this really interesting lesson ! All of this make sense :) I asked the question to increase my knowledge in term of "chip architecture", not really to improve my way of programming. The question is maybe useless nowadays but still interesting to me ;) – sphax Mar 24 '14 at 04:31
  • 1
    @sphax: For a nice example of how screwing up the chip's branch predictor can have a visible effect on performance see http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array – Eric Lippert Mar 24 '14 at 15:51

2 Answers2

3

The two comparisons sender == null and sender != null take the same amount of time*.

The best practice is to use whichever is most readable or understandable, and that will depend on the situation.

For example:

if (condition) {
    ...
    lots_of_code();
    ...
    return;
}
short_code();
return;

This would arguably be more readable if written as:

if (!condition) {
    short_code();
    return;
}
...
lots_of_code();
...
return;

In the second version, more code sits at a lower level of scope and hence it is often easier to understand.


*Note: if you are running this kind of check many millions of times and it does become a performance issue (unlikely), you need to understand a little about how the compiler works. Most compilers take something like:

if (condition) {
    do_something();
} else {
    do_other_thing();
}
return;

And produce instructions like:

    evaluate condition
    jump_if_false ELSECODE
    do_something()
    return

ELSECODE:
    do_other_thing()
    return

Skipping the jump when condition is true is usually slightly cheaper than performing the jump when it is false. It depends what is being done immediately after the if statement though. The compiler will often try to guess which branch is more likely at compile time and arrange the code accordingly, while the CPU may do branch prediction at runtime to optimise it in a different way regardless. With some languages/compilers you can give a hint that the condition is either highly likely or highly unlikely.

99.99% of time you should completely ignore this, but it becomes important in some rare cases (like if you were trying to write part of an operating system or emulator, or something for embedded devices).

codebeard
  • 2,356
  • 2
  • 13
  • 15
1

I think the efficiency will change depending on the variable type, so like Eric said, you would really need to measure it to find out.

However, if you are asking which way around you should write it, I can suggest that Option 2 is (usually) better. The reason being that it's one less mental step to read without the negation. Since code is written once and read many times, we should almost always make readability our number one priority. We should only start working on efficiency once we've proved we need to.

There's a great book called Code Complete that talks about this kind of stuff that I really recommend.

Ev.
  • 7,109
  • 14
  • 53
  • 87
  • I find that I read `if variable is not null, do this` more often, and thus I would prefer it. – clcto Mar 24 '14 at 04:08