I was curious as to the speed on switch
, believing that it was "very" fast, but I have a test case that seems to show a single switch is about as fast as about 4 if
tests, when I expected (no solid reason) it to be as fast as 1 test. Here's the two methods I wrote to compare switch
with if
:
public static int useSwitch(int i) {
switch (i) {
case 1: return 2;
case 2: return 3;
case 3: return 4;
case 4: return 5;
case 5: return 6;
case 6: return 7;
default: return 0;
}
}
public static int useIf(int i) {
if (i == 1) return 2;
if (i == 2) return 3;
if (i == 3) return 4;
if (i == 4) return 5;
if (i == 5) return 6;
if (i == 6) return 7;
return 0;
}
Here's my testing code:
long x = 0;
for (int i = 0; i < 999999; i++)
x += useIf(i % 7); // I use "x" so calls won't get optimized out
And another identical loop for useSwitch()
On my machine these loops take about the same time to complete, which was a surprise.
I arrived at the number of ifs as "4", because that's the average given the input range (I think).
If I reduce the number of logic options, the if
version is noticeably faster.
My question is:
Is it that switch
actually isn't that fast, or is this an "unfair" test in some way?