java – 在块中返回try块vs返回块

前端之家收集整理的这篇文章主要介绍了java – 在块中返回try块vs返回块前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在一个小的静态方法中有一个try语句,对于我应该从哪里返回是否有最佳实践?
try {
    mightThrow();
    return true;
} catch (Exception e) {
    return false;
}

或之后,

try {
    mightThrow();
} catch (Exception e) {
    return false;
}
return true;

功能上讲,这些应该预先形成相同的,实际上是否存在字节码差异?性能方面,它们是完全相同的吗?

或者是一个优先于另一个?哪个以及为什么?

解决方法

我没有听说过这个问题的实际最佳实践,但是你经常看到当方法使用过早返回时,返回true的情况是在底部,例如
public bool canReadFile(path) {
  if (!fileExists(path))  
    return false;

  if (!fileIsReadable(file))
    return false;

  ...
  return true;
}

因此,我建议您按照这种做法进行try / catch块.它还可以更快地查看“预期”返回值是什么.

关于字节码,那么是的,确实存在差异.我做了一个快速的示例程序

class TryBlock {
    public static void main(String[] args) {
        a();
        b();
    }

    public static boolean a() {
        try {
            System.out.println("A");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean b() {
        try {
            System.out.println("B");
        } catch (Exception e) {
            return false;
        }
        return true;
    }

}

然后编译它并检查字节码

$javac TryBlock.java; javap -c TryBlock
Compiled from "TryBlock.java"
class TryBlock {
  TryBlock();
    Code:
       0: aload_0
       // Method java/lang/Object."<init>":()V
       1: invokespecial #1                  
       4: return

  public static void main(java.lang.String[]);
    Code:
       // Method a:()Z
       0: invokestatic  #2                  
       3: pop
       // Method b:()Z
       4: invokestatic  #3                  
       7: pop
       8: return

  public static boolean a();
    Code:
       // Field java/lang/System.out:Ljava/io/PrintStream;
       0: getstatic     #4                  
       // String A
       3: ldc           #5                  
       // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       5: invokevirtual #6                  
       8: iconst_1
       9: ireturn
      10: astore_0
      11: iconst_0
      12: ireturn
    Exception table:
       from    to  target type
           0     9    10   Class java/lang/Exception

  public static boolean b();
    Code:
       // Field java/lang/System.out:Ljava/io/PrintStream;
       0: getstatic     #4                  
       // String B
       3: ldc           #8                  
       // Method java/io/PrintStream.println:(Ljava/lang/String;)V
       5: invokevirtual #6                  
       8: goto          14
      11: astore_0
      12: iconst_0
      13: ireturn
      14: iconst_1
      15: ireturn
    Exception table:
       from    to  target type
           0     8    11   Class java/lang/Exception
}

那么性能差异是什么?虽然我没有测试,但我的赌注是没有任何明显的东西.最重要的是,这几乎不是您的应用程序的瓶颈.

原文链接:https://www.f2er.com/java/120773.html

猜你在找的Java相关文章