tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From David kerber <dcker...@verizon.net>
Subject Re: Performance: switch vs if ... else if
Date Wed, 20 May 2009 12:18:10 GMT
Ronald Klop wrote:
> As with the tips about usage of char in the switch you can also test 
> using a char in the if ... else.
>
> if (myChr.length() != 1) {
>   throw new RuntimeException("invalid length");
> }
> char ch = myChr.charAt(0);
> if (ch == 'c') {
>  p += 1;
> } else if (ch == 'r') {
>  p += 2;
> } ...
>
> Should make a difference in performance also.
Thanks for that suggestion.

>
> And if you want to try more speed you can try to avoid the 
> conditionals in the code.
> private static final char OFFSET = 'a';
> private static final int[] VALUES = init();
>
> private static int[] init() {
>   final int[] tmp = new int[26];
>   tmp['c' - OFFSET] = 1;
>   tmp['r' - OFFSET] = 2;
>   tmp['l' - OFFSET] = 3;
>   tmp['a' - OFFSET] = 4;
>   tmp['t' - OFFSET] = 5;
>   tmp['d' - OFFSET] = 6;
>   return tmp;
> }
>
> private static int p = 0;
> private static void ifArray(final String myChr) {
>   final char ch = myChr.charAt(0);
>   p += VALUES[ch - OFFSET];
> }
This won't help in real life; the numeric incrementing in the demo code 
was just to be sure the optimizer didn't take too many shortcuts when I 
was speed testing.  The actual processing for each case in the real code 
is completely different.

D



---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


Mime
View raw message