Local variables before return statements, does it matter?

后端 未结 3 850
遇见更好的自我
遇见更好的自我 2020-12-02 19:20

Sorry if this is a newbie question but I couldn\'t find an answer for this. Is it better to do this:

int result = number/number2;
return result;
3条回答
  •  抹茶落季
    2020-12-02 19:45

    Compilers are usually smart enough to optimize this sort of thing as appropriate. See data-flow optimizations on Wikipedia.

    In this case, it will probably need to allocate a temporary variable to store the result even if you don't specify one yourself.

    Edit: Clashsoft is right about the bytecode compiler:

    $ cat a.java
    class a {
       public static int a(int x, int y) {
         return x / y;
       }
    
       public static int b(int x, int y) {
         int r = x/y;
         return r;
       }
    
       public static int c(int x, int y) {
         final int r = x/y;
         return r;
       }
    }
    $ javap -c a
    Compiled from "a.java"
    class a {
      a();
        Code:
           0: aload_0
           1: invokespecial #1                  // Method java/lang/Object."":()V
           4: return
    
      public static int a(int, int);
        Code:
           0: iload_0
           1: iload_1
           2: idiv
           3: ireturn
    
      public static int b(int, int);
        Code:
           0: iload_0
           1: iload_1
           2: idiv
           3: istore_2
           4: iload_2
           5: ireturn
    
      public static int c(int, int);
        Code:
           0: iload_0
           1: iload_1
           2: idiv
           3: istore_2
           4: iload_2
           5: ireturn
    }
    

提交回复
热议问题