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 switch is faster in that situation, because a loop would check the end condition several times, whereas a switch does it only once.
The best ways to improve loop performance are to decrease the amount of work done per iteration and decrease the number of loop iterations.
It is not necessarily an antipattern to use a switch statement within a loop—it is only considered incorrect when used to model a known sequence of steps. The most common example of the correct use of a switch within a loop is an inversion of control such as an event handler.
What is the advantage of switch over for loop or while loop? The main advantage is that in this the user can compare a no. Of values of a variable by a single switch statement and using a number of cases.
A switch
on 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 in doWork2(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:
You could do something like:
Func(void, int> doWork;
switch(way)
{
case 1:
doWork = doWork1;
break;
case 2:
doWork = doWork2;
break;
case 3:
doWork = doWork3;
break;
}
for (int i=0;i<count;i++)
{
doWork(i);
}
(Written in here, code might not quite compile, just to give you the idea...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With