Switch Optimization

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • lilburne

    #16
    Re: Switch Optimization

    Mike and Jo wrote:[color=blue]
    > "lilburne" Wrote:
    >[color=green]
    >>I suspect he has no such evidence. The compiler will convert
    >>a most switches into an ifelse sequence anyway.
    >>[/color]
    >
    >
    > After the replies I was given I wanted to see the actual gain in using
    > switch in the way I wanted. Being able to leave the comparison function
    > without comparing remaining expressions.
    >
    > I timed a switch function compared with an if/elseif/else function. In C++
    > the if/elseIf/else out performed the the switch by a factor of 1.29 in my
    > particular scenario. (If clause 90 ms / switch clause 116 ms based on 10
    > million iterations in total. Used values 0,1,2 in the order if 0/else if 1/
    > else). This MAY not be the case if you have a large number of expressions
    > to compare in the switch function. I would place the most likely
    > expressions near the begining of the switch function in hope that the break
    > would let me leave the function early and not compare the switch against all
    > other expressions. I did not run timings on this so I do not know for sure
    > (stop assuming things - check).
    >[/color]

    As you have seen the difference between a switch and the
    ifelse sequence is negligible: 26ms in 10,000,000
    executions. Unless your application is time sensitive to the
    extent that you need to count clock cycles micro
    optimizations of this nature are a waste of time. Also your
    descision today may well be invalidated by a compiler update.

    Use which ever construct is the clearer in the specific
    context. Some metrics consider that switch statements
    increase complexity. But in certain circumstances the switch
    conveys the programmers intent clearer than an ifelse.

    If you have a large number of expressions to compare you are
    probably better off reorganising the algorithm to reduce the
    number of expressions that need to be tested.

    Smarter algorithims and data structures will give far larger
    performance boost than choice of programming construct.

    Comment

    Working...