The Prototype Asked:2020-06-21 22:05:15 +0000 UTC2020-06-21 22:05:15 +0000 UTC 2020-06-21 22:05:15 +0000 UTC 什么是更快的检查 - “大于零”或“不等于零”? 772 用什么比较好? a > 0 或者 a != 0 在这两种情况下,假设我们对任何事情都不感兴趣,只是数字必须大于零。 这意味着在性能方面,什么更容易做 - 检查更多或不相等? java 1 个回答 Voted Best Answer Ramiz 2020-06-21T22:43:39Z2020-06-21T22:43:39Z 考虑一个测试类 public class OpsTest { public boolean gZero(int a) { return a > 0; } public boolean neZero(int a) { return a != 0; } } 在字节码中,我们看到以下内容: // Method descriptor #15 (I)Z // Stack: 1, Locals: 2 public boolean gZero(int a); 0 iload_1 [a] 1 ifle 6 4 iconst_1 5 ireturn 6 iconst_0 7 ireturn Line numbers: [pc: 0, line: 15] Local variable table: [pc: 0, pc: 8] local: this index: 0 type: OpsTest [pc: 0, pc: 8] local: a index: 1 type: int Stack map table: number of frames 1 [pc: 6, same] // Method descriptor #15 (I)Z // Stack: 1, Locals: 2 public boolean neZero(int a); 0 iload_1 [a] 1 ifeq 6 4 iconst_1 5 ireturn 6 iconst_0 7 ireturn Line numbers: [pc: 0, line: 20] Local variable table: [pc: 0, pc: 8] local: this index: 0 type: OpsTest [pc: 0, pc: 8] local: a index: 1 type: int Stack map table: number of frames 1 [pc: 6, same] 我们看到区别在于 ifle 和 ifeq 运算符,因此,正如评论中已经提到的,性能上没有(有形的)差异,以可读的方式编写代码。
考虑一个测试类
在字节码中,我们看到以下内容:
我们看到区别在于 ifle 和 ifeq 运算符,因此,正如评论中已经提到的,性能上没有(有形的)差异,以可读的方式编写代码。