Skip to main content

Optimizations for swtich statement

2 replies [Last post]
Joined: 2005-03-15

What optimizations does hotspot have for switch statement? For example, if I have a switch with many cases (all the case values are constants):

protected Object invokeGetterForIndex(int index) throws Exception
switch (index)
case IDCOL:
return getIdCol();
return getVarcharCol1();
return getVarcharCol2();
return getVarcharCol3();
.. .. ..
case DATECOL8:
return getDateCol8();
case DATECOL9:
return getDateCol9();
return null;

Does hotspot evaluate it as a big if-else statement or are there some optimizations that will be done? I found an article describing some potential optimizations (, but wasn't sure if whether hotspot does any of them or whether it works only if I'm returning constant values (in this case I need to call a method for each case).

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2004-11-29

In the server compiler, we apply the usual optimizations that you'll find in more statically compiled languages. If there are N cases and they are not "compact" (sequential or nearly sequential) then the compiler emits a decision tree of depth about log N. If the cases are compact, the compiler often emits a jump table. The two tactics can be mixed, with jump tables at the leaves of the decision tree. The profile tells us which cases are hottest, and could help us adjust the decision tree balance, but we don't do much with that information yet. In particular, if just one or two cases are hot, we don't yet make a fast path for them. (That would be a good starter project for the open source.) That's about it.

It looks like your code has a compact set of cases in some range [0..N-1]. If so, you're probably getting jump tables from the server compiler.

Joined: 2004-01-07

I remember a blog where a new optimization hotspot does for switch statements was presented.
It does not generate else-if code (I guess it never did but I may be wrong) and even generates for small switch-statements some special i386 code.

lg Clemens