java - && 在 if() 中的重要性

标签 java

我想知道这两个代码在性能上有什么区别。

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/

相关文章:

java - 测试server.xml中配置的所有数据源

Java System.nanoTime 经过的平均时间不断变小

java - 如何返回 DocumentSnapShot 作为方法的结果?

java - 使用泛型来替换特定的类类型

java - 无需大量循环即可确定字符串数组中的值是否相等

java - Java 8 上的 Google App Engine - 开发人员无法使用 java.time。服务器?

java - 在Java Android应用程序中获取ruby环境变量DATABASE_URL

Java 用空白分隔符分割字符串

java - SpringBoot直接MongoRepository到特定的MongoTemplate

java - 您将全局应用程序数据放在 Linux 上的什么位置(特别是 Mint 13)?