1

我想知道这两个代码之间的性能有什么区别。

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 不为空,那么只有它会进入块。第二段代码也是如此。我想知道的是性能或更好的编码标准有什么区别,为什么?

4

4 回答 4

14

如果您询问性能,您应该始终测量. 但是不,应该没有区别。此外,如果是你唯一的性能问题代码,那么我真的很羡慕你。

至于编码标准。更少的嵌套几乎总是更好地阅读和遵循。这意味着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       
于 2012-06-08T08:02:39.437 回答
9

正如其他人所说,性能应该没有任何差异。小提示 - equals几乎总是调用instanceof,它为 null 返回false。所以写:

if( !"".equals(foo)) {...}

做同样的检查并且是空安全的。

于 2012-06-08T08:17:14.927 回答
2

两者在性能方面没有区别。因为在第一种情况下它会检查一个条件,如果失败则不会进入内部。在第二种情况下,JVM 也会检查第一个条件,如果它返回 false,那么 JVM 将永远不会进行第二次检查。如果 first 为false ,逻辑 && 运算符将始终为false

在编码标准方面,我会选择第二个选项,因为它的编码行数较少。

于 2012-06-08T08:07:21.350 回答
1

由于在编译时执行优化,bytcode生成的很可能会被优化。if(sample!=null && !sample.equals(""))java

如果您谈论的是您编写的实际代码,最好只有一个if. 由于两个的结构if对于编译器来说更复杂(没有优化)。虽然我没有经验数据来支持这一点。

于 2012-06-08T08:04:09.090 回答