Michael C said:
It has to do a comparison to each value presumably starting at the top.
Putting a commonly used item towards the bottom should result in more
comparisons.
That's not how switch/case works - at least not when there are lots of
contiuguous entries. A table is used instead, to avoid doing that many
comparisons. When the entries are sparse, things get a bit trickier -
but I doubt that the performance is improved by moving things around. I
believe (after a short time of investigation, but nothing conclusive)
that the compiler will compile the code of the cases in the order you
specify, but do the comparisons in the same way whatever you do, just
jumping to different places. Of course, the JIT gets another stab at
optimisation too.
That's the thing with these micro-optimisations - they're *definitely*
not worth doing if you don't even know whether they'll help. The time
spent benchmarking this kind of thing (unless you happen to just be
interested and do it in spare time) is likely to be far more
"expensive" than any performance gains achieved.
You could use the DebuggerStepThroughAttribute.
That's the one!
It used to be applied to the designer generated code in InitializeComponent
I believe but doesn't look like it is anymore.
I don't think there's much difference in readability myself so use the
faster.
Well, there isn't much difference in readability - but there isn't much
difference is speed either. I think in most cases you're more likely to
waste a second of engineering time reading the code than you are to
waste a second of computing time running the slower code. I value
engieneering time higher than computing time.
Interesting. I would have used #1 when I needed the index.
Again, making the code a bit less readable for a minute difference in
speed, which may even be the wrong way!
Generally I would use #3 but wouldn't think it was the end of the world if
#1 or #2 was used when #3 could have been. It's possible you are
"micro-optimising" readability if you are using things like (X=="") instead
of len because of readability. I wouldn't consider readability down to that
level.
Whereas I view readability as absolutely king. Anything which
interrupts the flow of thoughts even slightly could cost time. In this
case, having an extra variable to think about could easily make someone
have to check something they wouldn't have to otherwise. (Heck, to
start with you need to check that the loop bounds look correct.)
The thing about this is that I don't have to deviate from natural
coding to do it - the most natural way of expressing the code when you
think of it in the first place is usually the most natural way of
reading it too. That's not true when you start bending the code to
achieve performance gains which will be negligible if they exist at
all.