Java switch cases: with or without braces?

cdmckay picture cdmckay · Mar 11, 2009 · Viewed 45.6k times · Source

Consider the following two snippets, with braces:

switch (var) {
  case FOO: {
    x = x + 1;
    break;
  }

  case BAR: {
    y = y + 1;
    break;
  }
}

Without braces:

switch (var) {
  case FOO:
    x = x + 1;
    break;

  case BAR:
    y = y + 1;
    break;
}

I know that, in the snippet with braces, a new scope is created by enclosing each case in braces. However, if each case does not need the new scope (i.e. no variable names are being reused), is there any sort of performance penalty for using the braces with a case?

Answer

MrValdez picture MrValdez · Mar 11, 2009

is there any sort of performance penalty for using the braces with a case?

None.

The curly braces are there to help the compiler figure out the scope of a variable, condition, function declaration, etc. It doesn't affect the runtime performance once the code is compiled into an executable.