Peculiar fruits in the JDK

Ulf Zibis Ulf.Zibis at CoSoCo.de
Wed Jun 25 16:33:46 UTC 2008


Hi David,

please don't CC to me. Otherwise I get your message twice. I read the list.

....

Am 25.06.2008 17:55, David M. Lloyd schrieb:
> On 06/25/2008 03:57 AM, Ulf Zibis wrote:
>> Hi David,
>>
>> can you show an example using a 'switch' statement which is shorter 
>> or faster than:
>>
>>            char c = c2bMap.charAt(c2bMapIndex[(current & MASK1) >> 
>> SHIFT] + (current & MASK2));
>
> Faster - maybe or maybe not; but the "c2bMap", being sparse, can be 
> represented possibly more space-efficiently using a lookupswitch (I'm 
> thinking of all the \u0000 entries, which can be handled with a 
> "default" branch):
>
>     public static final c2bMapper(int idx) {
>         switch (idx) {
>             case 1: return 1;
>             case 2: return 2;
>             ...
>             default: return 0;
>         }
>     }
>
> The primary disadvantage being, I guess, that the table cannot then be 
> stored in e.g. a properties file.
>
> - DML
>
>
Let me correct:

    public static final byte c2bMapper(char inChar) {
        int idx = (int)inChar;
        switch (idx) {
            case 0x0001: return (byte)0x01;
            case 0x0002: return (byte)0x02;
            ...
            case 0x015F: return (byte)0x8F;
            ...
            case 0x02DD: return (byte)0x64;
            default: return 0;
        }
    }

Internally this will be compiled as a looong if () else if () else if () 
.... chain, because the cases are NOT consecutive. Executing such a 
chain will never be faster, than calculating the index as I posted.

Additionally this code would not be space-efficient. Think about 256 
times {else if (idx == x) return (byte)y;}
Not to forget: each of the around 100 encoders will need such an 
individual custom switch-case block. :-(

- Ulf





More information about the core-libs-dev mailing list