Switches
The
Java bytecode specification allows a switch
statement to be compiled into one of two different bytecodes. One
compiled switch
type works as follows:
Given a particular value passed to the
switch
block to be compared, the passed value is successively compared against the value associated with each case statement in order. If, after testing all cases, no statements match, then the default label is matched. When acase
statement that matches is found, the body of that statement and all subsequentcase
bodies are executed (until one body exits theswitch
statement, or the last one is reached).
The operation of this switch
statement is
equivalent to holding an ordered collection of values that are
compared to the passed value, one after the other in order, until a
match is determined. This means that the time taken for the
switch
to find the case that matches depends on
how many case
statements there are and where in
the list the matched case is. If no cases match, and the
default
must be used, that always takes the
longest matching time.
The other switch
bytecode works for
switch
statements where the case values all lie in
a particular range (or can be made to lie in a particular range). It
works as follows:
Given a particular value passed to the
switch
block to be compared, the passed value is tested to see if it lies in the range. If it does not, thedefault
label is matched; otherwise, the offset of the case is calculated and the corresponding case is matched directly. ...
Get Java Performance Tuning now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.