2009/5/19 David kerber <[email protected]>:
> Caldarale, Charles R wrote:
>>>
>>> From: David kerber [mailto:[email protected]]
>>> Subject: Performance: switch vs if ... else if
>>>
>>> I had to process based on a parameter that could take
>>> one of 6 different single-character string values. I
>>> had been using an if .. else if construct.
>>>
>>
>> Interesting numbers. Can you show us the exact code of the if .. else
>> construct?
>>
>> - Chuck
>>
>
> Here is the entire code. The variables o and p are used to make sure there
> is actually some work done in each call to the test methods. I've seen
> cases (mainly in Delphi) where an optimizer completely removed large chunks
> of code because it wasn't doing anything. I don't know of java can do that
> or not...
>
> public class SwitchVsIfTest {
> (...)
>
1. If you are doing tests with the classic VM, allow it some time to warmup and
compile your code. That is, run the same test first with a smaller count of
iterations.
Server VM precompiles code before using it, while Classic one compiles
heavily used parts of code on-the-fly.
2. This line:
rtFields.valueOf( myChr )
does all the job that your if/elif/else tree did. That is, I expect
that all the time
is spent in there, not in switch(number) that follows it.
3. You can try the following:
private static void switchSub2( String myChr ) {
if (myChr.length() != 1) {
throw new AssertionError();
}
switch ( myChr.charAt(0)) {
case 'c':
o += 1;
break;
case 'r':
o += 2;
break;
case 'l':
o += 3;
break;
case 'a':
o += 4;
break;
case 't':
o += 5;
break;
case 'd':
o += 6;
break;
}
return;
}
Best regards,
Konstantin Kolinko
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]