Reputation: 33
for instance, I have two versions of a simple count loop - both achieve the same thing but one is more efficient (and presumably uses less memory) than the other. See below:
CODE 1:
int num;
for (num =0; num<10; num++){
System.out.println(num);
}
CODE 2:
for (int num=0; num<10; num++){
System.out.println(num);
}
Upvotes: 1
Views: 55
Reputation: 54801
They compile identically and so have identical performance and memory requirements.
For proof look at the compiled java byte code using javap -c <classfile>
Code:
public static void a() {
for (int num = 0; num < 10; num++) {
System.out.println(num);
}
}
public static void b() {
int num;
for (num = 0; num < 10; num++) {
System.out.println(num);
}
}
Byte code:
public static void a();
Code:
0: iconst_0
1: istore_0
2: goto 15
5: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
8: iload_0
9: invokevirtual #21 // Method java/io/PrintStream.println:(I)V
12: iinc 0, 1
15: iload_0
16: bipush 10
18: if_icmplt 5
21: return
public static void b();
Code:
0: iconst_0
1: istore_0
2: goto 15
5: getstatic #15 // Field java/lang/System.out:Ljava/io/PrintStream;
8: iload_0
9: invokevirtual #21 // Method java/io/PrintStream.println:(I)V
12: iinc 0, 1
15: iload_0
16: bipush 10
18: if_icmplt 5
21: return
Upvotes: 3