please help me to identify which of these following is more optimized code?
for(int i=0;i<count;i++)
{
switch(way)
{
case 1:
doWork1(i);
break;
case 2:
doWork2(i);
break;
case 3:
doWork3(i);
break;
}
}
OR
switch(way)
{
case 1:
for(int i=0;i<count;i++)
{
doWork1(i);
}
break;
case 2:
for(int i=0;i<count;i++)
{
doWork2(i);
}
break;
case 3:
for(int i=0;i<count;i++)
{
doWork3(i);
}
break;
}
In the first case, there happens to be an overhead of always checking the switch case condition in every iteration. In second case, the overhead is not there. I feel the second case is much better. If anyone has any other workaround, please help me out in suggesting it.
A
switchon low, contiguous values is insanely fast – this type of jump has highly optimised handling. Frankly, what you ask will make no difference whatsoever in the vast majority of cases – anything indoWork2(i);is going to swamp this; heck, the virtual-call itself might swamp it.If it really, really, really matters (and I struggle to think of a real scenario here), then: measure it. In any scenario where it is noticeable, then only way to measure it will be with your actual, exact code – you can’t generalise pico-optimisations.
So: