jbranchaud
jbranchaud

Reputation: 6087

Representation and efficiency of Switch statements in bytecode?

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.

Upvotes: 4

Views: 2617

Answers (2)

Louis Ricci
Louis Ricci

Reputation: 21106

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

Upvotes: -1

Amir Afghani
Amir Afghani

Reputation: 38541

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.

Upvotes: 5

Related Questions