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