Java交换机案例:有或没有大括号? [英] Java switch cases: with or without braces?

查看:93
本文介绍了Java交换机案例:有或没有大括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下两个片段,带括号:

Consider the following two snippets, with braces:

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

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

没有大括号:

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?

推荐答案


对于案例使用大括号是否有任何性能损失?

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

无。

花括号可以帮助编译器找出变量,条件,函数声明等的范围。它不会一旦代码编译成可执行文件,就会影响运行时性能。

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.

这篇关于Java交换机案例:有或没有大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆