I was faced with this question by my team leader.
Statement 1 (written by me):
lnkbtn1.visible = lnkbtn2.visible = lnkbtn.visible = false;
Statement 2 (written by my team leader):
lnkbtn1.visible = false;
lnkbtn2.visible = false;
lnkbtn3.visible = false;
Which statement is better and why?
4
The performance difference will be so incredibly minor that you should never even think about it.
The only thing that matters here is what one you would rather be using.
The first option might be in one line but oneliners aren’t necessarily better.
It is harder to read and your approach also means that if you want to have false-true-false, you would have to retype everything.
The second option is very clear and each statement is self contained, I would go with this.
1
There’s no difference in performance at all. They will compile to virtually identical IL1.
However, there is a difference in readability and code style. The first option may be more compact, but the second is clear and conforms to most .NET coding guidelines. I personally prefer the second.
1. I ran a simple test in LINQPad. The only difference between the two options was in how the false
value was loaded on the stack between calls to set_Visible
. The first option produced one ldc.i4.0
and two dup
‘s while the second produced three ldc.i4.0
‘s.
4
What about a more DRY version, where even the code visible =
is not repeated over and over again?
foreach(var btn in new[]{lnkbtn1, lnkbtn2, lnkbtn3})
btn.visible=false;
IMHO that will scale better when the number of buttons increase, or the number of properties of each button which has to be initialized increases.
2
I have to say I prefer the first option. It is crystal clear that all values are being set to false.
With the second option I’m having to read every line and wonder why it isn’t all on one line following DRY principles due the redundant literal.
I’d find it hard to justify the second case on the grounds that the values might change at some point in the future. So much code cruft comes about because of something the programmer thought might happen but never did. This code then has to be tested and maintained. Not to mention being read by potentially dozens of programmers over the course of its life.
6
Just because somebody’s a “team leader” doesn’t mean much.
If .visible
is nothing more than a simple boolean variable, the difference in cost is either zero or basically nothing.
However, if .visible
is a property, all bets are off.
Assigning to a property is one method call, and retrieving the value is another.
In that case, the separate assignments might be faster, but watch out for another problem.
Properties have some nice properties (!), but I’ve seen them treated as if they were free, performance-wise, when in fact they can be major sink-holes of CPU time if they are implemented recursively.
In terms of style, I take a dim view of giving this more than a nanosecond of thought.
Nearly all serious software has far bigger issues than this.