Clashsoft
Clashsoft

Reputation: 11882

TABLESWITCH Performance Increase?

Say I have the following switch statement:

switch (i)
{
    case 0: ...; return ...;
    case 1: ...; return ...;
    case 2: ...; return ...;
    case 400: ...; return ...;
    case 401: ...; return ...;
    case 402: ...; return ...;
}

Since the gaps are too large for the compiler to generate a reasonable TABLESWITCH (O(1) complexity) instruction here, it uses a LOOKUPSWITCH (O(log n) complexity). Would it be possible to increase the performance of this code by splitting the switch into two like this:

switch (i)
{
    case 0: ...; return ...;
    case 1: ...; return ...;
    case 2: ...; return ...;
}

switch (i)
{
    case 400: ...; return ...;
    case 401: ...; return ...;
    case 402: ...; return ...;
}

This would cause the compiler to generate two TABLESWITCH instead of one LOOKUPSWITCH.

Upvotes: 0

Views: 204

Answers (1)

apangin
apangin

Reputation: 98560

Do not spend much time trying to optimize the bytecode. The bytecode does not necessarily reflect the performance of JIT-compiled methods. Why don't you take JMH and check the actual performance of both cases yourself?

In fact, HotSpot C2 compiler treats tableswitch and lookupswitch in a similar way, and it takes care of lookupswitch that has sequential labels with gaps very well.

Both cases are translated into a sequence of compare and conditional jump instructions in a binary search-like manner and work almost identically performance-wise.

Upvotes: 2

Related Questions