ซ้ำได้:
คุณประกาศตัวแปรที่ไหน ด้านบนของวิธีการหรือเมื่อคุณต้องการ?
มันสร้างความแตกต่างถ้าฉันประกาศตัวแปรภายในหรือภายนอกวงใน Java?
นี่คือ
for(int i = 0; i < 1000; i++) {
   int temp = doSomething();
   someMethod(temp);
}
เท่ากับนี้ (เกี่ยวกับการใช้หน่วยความจำ)
int temp = 0;
for(int i = 0; i < 1000; i++) {
   temp = doSomething();
   someMethod(temp);
}
และถ้าตัวแปรชั่วคราวเป็นตัวอย่างของ ArrayList
for(int i = 0; i < 1000; i++) {
   ArrayList<Integer> array = new ArrayList<Integer>();
   fillArray(array);
   // do something with the array
}
แก้ไข: javap -cฉันได้รับผลลัพธ์ต่อไปนี้
ตัวแปรนอกลูป:
  public static void main(java.lang.String[]);
    Code:
       0: iconst_0      
       1: istore_1      
       2: iconst_0      
       3: istore_2      
       4: iload_2       
       5: sipush        1000
       8: if_icmpge     25
      11: invokestatic  #2                  // Method doSomething:()I
      14: istore_1      
      15: iload_1       
      16: invokestatic  #3                  // Method someMethod:(I)V
      19: iinc          2, 1
      22: goto          4
      25: return  
ตัวแปรภายในลูป:
  public static void main(java.lang.String[]);
    Code:
       0: iconst_0      
       1: istore_1      
       2: iload_1       
       3: sipush        1000
       6: if_icmpge     23
       9: invokestatic  #2                  // Method doSomething:()I
      12: istore_2      
      13: iload_2       
      14: invokestatic  #3                  // Method someMethod:(I)V
      17: iinc          1, 1
      20: goto          2
      23: return        
และสำหรับความสนใจรหัสนี้:
public class Test3 {
    public static void main(String[] args) {
        for(int i = 0; i< 1000; i++) {
            someMethod(doSomething());
        }   
    }
    private static int doSomething() {
        return 1;
    }
    private static void someMethod(int temp) {
        temp++;
    }
}
ผลิตสิ่งนี้:
  public static void main(java.lang.String[]);
    Code:
       0: iconst_0      
       1: istore_1      
       2: iload_1       
       3: sipush        1000
       6: if_icmpge     21
       9: invokestatic  #2                  // Method doSomething:()I
      12: invokestatic  #3                  // Method someMethod:(I)V
      15: iinc          1, 1
      18: goto          2
      21: return   
แต่การเพิ่มประสิทธิภาพเกิดขึ้นที่รันไทม์แล้ว มีวิธีดูรหัสที่ได้รับการปรับปรุงหรือไม่? (ขออภัยสำหรับการแก้ไขที่ยาว)