问题
Though a switch statement can be represented as a series of if statements, it appears that when a Java switch statement is compiled into bytecode, a different approach is used.
- What is the representation used by bytecode?
- I assume this alternate representation is for efficiency reasons, so how does the efficiency compare to that of just an if statement representation?
- Are there any other considerations that have led to using this representation?
回答1:
Read the spec . In Java, if you code a switch statement, then depending on various things the switch is converted into a tableswitch instruction in bytecode. Essentially a jump table. What the bytecode looks like may be irrelavent though, if the JIT can optimize it into something more efficient. This is of course, platform dependent.
回答2:
Consider this simple JavaScript example
var SwitchCases = [
// case 1
function() { return "one"; },
// case 2
function() { return "two"; },
// case 3
function() { return "three"; },
// default
function() { return ""; }
];
var SwitchCaseMin = 1;
var SwitchCaseMax = 3;
var SwitchCaseDefault = true;
function FakeSwitchCase(switch) {
if(switch > SwitchCaseMax || switch < SwitchCaseMin) {
if(SwitchCaseDefault == true) {
return SwitchCases[SwitchCases.length-1]();
}
} else {
return SwitchCases[switch - SwitchCaseMin]();
}
}
The key part is
SwitchCases[switch - SwitchCaseMin]();
Imagine if there were many cases the code that evaluates them wouldn't grow any larger, but if we used IF..ELSE IF...ELSE the execution time would grow with each added case.
In a real switch case implementation SwitchCases (from the above code) would be an array/look-up-table of Labels (read: offsets) to the locations in the function where the Case code blocks appeared.
EDIT
In java the above switch case would be compiled to the following byte code
[tableswitch 0xAA]
[padding bytes 0x00 or 0x0000 or 0x000000]
[offset of SwitchCases[3]] // default case
[SwitchCaseMin] // 1
[SwitchCaseMax] // 3
[offset of SwitchCases[0]] // case 1
[offset of SwitchCases[1]] // case 2
[offset of SwitchCases[2]] // case 3
来源:https://stackoverflow.com/questions/8748837/representation-and-efficiency-of-switch-statements-in-bytecode