我想知道这两个代码在性能上有什么区别。
String sample="hello";
if(sample!=null)
{
if(!sample.equals(""))
{
// some code in here
}
}
或
String sample="hello";
if(sample!=null && !sample.equals(""))
{
// some code in here
}
据我所知,在第一个代码中,如果 sample 不为空,那么只有它会进入 block 。第二段代码也是如此。 我想知道的是性能或更好的编码标准有什么区别,为什么?
最佳答案
如果您询问性能,您应该始终测量。但是不,应该没有区别。此外,如果那是您唯一有性能问题的代码,那么我真的很羡慕您。
至于编码标准。更少的嵌套几乎总是更易于阅读和遵循。这意味着最好将两者放在一个 if
中,尤其是因为它们是相关的。图案
if (check_foo_for_null && compare_foo)
非常常见,因此比另一个嵌套的 if
更不令人惊讶。
编辑:备份:
我有两个小方法:
static boolean x(String a) {
if (a != null && a.equals("Foo"))
return true;
else return false;
}
static boolean y(String a) {
if (a != null) {
if (a.equals("Foo")) {
return true;
} else return false;
} else return false;
}
产生以下代码:
static boolean x(java.lang.String);
Code:
0: aload_0
1: ifnull 15
4: aload_0
5: ldc #16 // String Foo
7: invokevirtual #21 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
10: ifeq 15
13: iconst_1
14: ireturn
15: iconst_0
16: ireturn
static boolean y(java.lang.String);
Code:
0: aload_0
1: ifnull 17
4: aload_0
5: ldc #16 // String Foo
7: invokevirtual #21 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
10: ifeq 15
13: iconst_1
14: ireturn
15: iconst_0
16: ireturn
17: iconst_0
18: ireturn
所以除了一个无关的 else
跳转目标之外,代码是相同的。如果你连 else
都没有:
static boolean z(String a) {
if (a != null) {
if (a.equals("Foo"))
return true;
return false;
}
那么结果真的是一样的:
static boolean z(java.lang.String);
Code:
0: aload_0
1: ifnull 15
4: aload_0
5: ldc #16 // String Foo
7: invokevirtual #21 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
10: ifeq 15
13: iconst_1
14: ireturn
15: iconst_0
16: ireturn
关于java - && 在 if() 中的重要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10945111/