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
switchblock 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 acasestatement that matches is found, the body of that statement and all subsequentcasebodies are executed (until one body exits theswitchstatement, 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
switchblock to be compared, the passed value is tested to see if it lies in the range. If it does not, thedefaultlabel is matched; otherwise, the offset of the case is calculated and the corresponding case is matched directly. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access