java efficiency comparison in terms of memory allocation

谁都会走 提交于 2019-12-02 01:38:59

One easy way to see if there's a difference is to examine the bytecodes.

The first version compiles to:

  public static void f();
    Code:
       0: bipush        100
       2: istore_0      
       3: iconst_0      
       4: istore_1      
       5: goto          26
       8: iconst_0      
       9: istore_2      
      10: goto          18
      13: iconst_3      
      14: istore_3      
      15: iinc          2, 1
      18: iload_2       
      19: iload_0       
      20: if_icmplt     13
      23: iinc          1, 1
      26: iload_1       
      27: iload_0       
      28: if_icmplt     8
      31: return        

whereas the second compiles to:

  public static void g();
    Code:
       0: bipush        100
       2: istore_3      
       3: iconst_0      
       4: istore_0      
       5: goto          26
       8: iconst_0      
       9: istore_1      
      10: goto          18
      13: iconst_3      
      14: istore_2      
      15: iinc          1, 1
      18: iload_1       
      19: iload_3       
      20: if_icmplt     13
      23: iinc          0, 1
      26: iload_0       
      27: iload_3       
      28: if_icmplt     8
      31: return        

If you compare them closely, you'll see that they are essentially identical.

Stylistically, I think it's preferable to declare variables as close as possible to their first use. With this in mind, I'd choose the first version over the second.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!