I'm developing a code with lots of iterations
and I was wondering which one of these conditions is more efficient.
//1
Boolean.FALSE.equals(x)
//2
x == false
//3
!x
I am using the first one but i am not sure about it. If someone can give some information and help me I will appreciate it.
The second and third one shoud be the fastest. The first one involves extra overhead, although it could well be that the JIT compiler optimises it.
The issue is more about readability. The first one is practically unreadable.
At popular request, I've expanded the answer a bit. I wrote this class:
package com.severityone.test;
public class Main {
public static void main(String[] args) {
final boolean x = false;
final boolean a = Boolean.FALSE.equals(x);
final boolean b = x == false;
final boolean c = !x;
}
}
This is the resulting byte code:
Compiled from "Main.java"
public class com.severityone.test.Main {
public com.severityone.test.Main();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: getstatic #2 // Field java/lang/Boolean.FALSE:Ljava/lang/Boolean;
5: iconst_0
6: invokestatic #3 // Method java/lang/Boolean.valueOf:(Z)Ljava/lang/Boolean;
9: invokevirtual #4 // Method java/lang/Boolean.equals:(Ljava/lang/Object;)Z
12: istore_2
13: iconst_1
14: istore_3
15: iconst_1
16: istore 4
18: return
}
What we can see from here is that numbers 2 and 3 take two instructions each, whereas number 1 takes five. For most programs, it won't make any difference, but if you're running in a tight loop, it could make a difference.
As for readability, the adage of "less is more" goes. Because my eyes aren't exactly 100%, I have problems with large amounts of text, so I prefer to put plenty of whitespace in my code. If you need to write Boolean.FALSE.equals(x), and it's actually the x that you're interested in, you need to mentally swap the whole thing around.
As for the other two, readability is mostly a matter of personal preference. There's something to be said for all three options:
!x
x == false
false == x
The ! can be easy to overlook if you have a very long expression, such as !((value < 0 || value > 10) && "yes".equals(response)). Some people prefer to write ... == false or false == ..., because you don't easily miss it.
Related
I think the question should be self explanatory, and the language I'm thinking about right now is Java, but it probably applies across all languages.
That being said, basically what I'm talking about is whether this:
// Initialize first
int i = 0;
for (i = 0; i < x; i++) {
// do some stuff
}
for (i = 0; i < x; i++) {
// do some more stuff
}
for (i = 0; i < x; i++) {
// do other stuff
}
Is better than this:
// Initializing i in the for loop
for(int i = 0; i < x; i++) {
// do some stuff
}
for(int i = 0; i < x; i++) {
// do some more stuff
}
for(int i = 0; i < x; i++) {
// do other stuff
}
This is a performance question, and I'm talking about initializing once /per/ scope resolution.
I performed a performance test with x=10 to evaluate the performance difference between the in-loop declaration method and the out-of-loop declaration method.
Details: I ran the code 300x with in-loop first and then 300x with out-of-loop first. Each run, I recorded the total runtime in nanoseconds to execute each method 10,000 times. So, I recorded a total of 1200 observations (600 per method). To measure steady-state performance (vice startup performance), I removed the 20 observations from each data set that had the longest duration. (The mean runtime for the 20 startup observations was an order of magnitude larger than the mean runtime for all the other observations.)
Results: A single-factor ANOVA indicates that the in-loop declaration is faster than the out-of-loop declaration (p-value=8.12584E-07). The mean runtimes were 158635.4931 nanoseconds for in-loop and 166943.7397 nanoseconds for out-of-loop. From a practical standpoint, we're talking about a difference of ~0.01ms per 10,000 iterations.
Conclusion: Just use the in-loop declaration. #FallAndLearn also points out that the in-loop declaration is easier to maintain because the local variable i is declared with the smallest scope possible .
You first piece of code is better than second one because int is a value type and its value is stored in stack once you initialize it , later on you just assign that type a value again and again .
On the other hand (second piece of code )you are initializing i three times i.e. creating stack entries three times .
So the first piece of code is better than the second one , performance wise .
The scope of local variables should always be the smallest possible.
Hence if int i is not used outside the loop then second way is always better. More readable too.
Performance wise they are both same. From a maintenance perspective, second option is better.
Also, the answers to this question will depend on your requirement. If your code has other data dependent on i or have only three for loops statement.
Let's check out the disassembled code for the following snippet:
public class Test {
public static void main(String[] args) {
int i = 0;
for(i = 0; i < 3; i++){
//do some stuff
}
}
}
public class Test {
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iconst_0
3: istore_1
4: iload_1
5: iconst_3
6: if_icmpge 15
9: iinc 1, 1
12: goto 4
15: return
}
Now let's generate another one for the initialization of the control variable inside the loop:
public class Test {
public Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: iconst_3
4: if_icmpge 13
7: iinc 1, 1
10: goto 2
13: return
}
They're not the same, I'm not a byte-code expert but I can tell that the second one has less overhead. The first one pushes int constant twice (the two iconst_<i> instructions), and has two istore_<n> instructions, compared to one instruction in the second code.
So, lets say I have this piece of code:
int mode = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB ? AudioManager.MODE_IN_COMMUNICATION : AudioManager.MODE_IN_CALL;
Now, lets say I run this code on some device that is pre-gingerbread.
Is there any case in which the non-available static import of AudioManager.MODE_IN_COMMUNICATION would be hit?
What I mean is, is there any scenario in which I would see a crash due to the MODE_IN_COMMUNICATION which is not available pre gingerbread being checked?
How does the ternary operator compile in Java? Does it compile these two things as ints? Does it expand the code during compilation?
A static final "variable" that is known at compile time is compiled into your code under certain circumstances. (e.g. every int where the compiler knows the final value)
So your code is actually just
int mode = android.os.Build.VERSION.SDK_INT >= 11 ? 3 : 2;
And any version can run that. It's not making any references to the constants that may or may not exist on the Android device.
The technical details can be found within the Java Language Specifiction e.g. §13.1
References to fields that are constant variables (§4.12.4) are resolved at compile time to the constant value that is denoted. No reference to such a field should be present in the code in a binary file
You can see from the documentation if something is such a constant value.
Build.VERSION_CODES.HONEYCOMB "Constant Value: 11"
AudioManager.MODE_IN_COMMUNICATION "Constant Value: 3"
AudioManager.MODE_IN_CALL "Constant Value: 2"
Build.VERSION.SDK_INT is itself a static final int but is not inlined at compile time. The documentation does not state a constant value
Build.VERSION.SDK_INT
It is implemented as
public static final int SDK_INT = SystemProperties.getInt("ro.build.version.sdk", 0);
and the compile can't figure out what SystemProperties.getInt will return so this value is the only one that actually references a value from within your device.
Scroll to the bottom of my answer to see what the actual javac source code does :)
The Bytecode Generated
#zapl's answer definitely answers the specific question, but I feel like the OP's question still wasn't answered. How exactly does JVM compile ternary operators? So, I just want to answer that question for everyone wondering.
We can figure this out by looking at the actual bytecode generated. So, I created a test where I have two outside classes that have some static variable I'm referencing, and all that, but that's still besides the point because we just want to know if it compiles it the same way as an if-else. Regardless, I did a test with ternary and with the equivalent if-else and these are the results.
Java Code:
class main {
public static void main(String[] args) {
int a = 0;
int b = 2;
int c = a > b ? MyBigClass.VAR_1 : MyOtherBigClass.VAR_2;
//int c;
// if (a > b) {
// c = MyBigClass.VAR_1;
// } else {
// c = MyOtherBigClass.VAR_2;
// }
}
}
class MyBigClass {
public static int VAR_1 = 0;
}
class MyOtherBigClass {
public static int VAR_2 = 1;
}
As you can see I commented out the if-else for the test with the ternary, and then I just commented out the ternary when I was testing the if-else. The bytecode that resulted was this.
Bytecode using if-else:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iconst_2
3: istore_2
4: iload_1
5: iload_2
6: if_icmple 16
9: getstatic #2 // Field MyBigClass.VAR_1:I
12: istore_3
13: goto 20
16: getstatic #3 // Field MyOtherBigClass.VAR_2:I
19: istore_3
20: return
Bytecode using the ternary:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iconst_2
3: istore_2
4: iload_1
5: iload_2
6: if_icmple 15
9: getstatic #2 // Field MyBigClass.VAR_1:I
12: goto 18
15: getstatic #3 // Field MyOtherBigClass.VAR_2:I
18: istore_3
19: return
The resulting bytecode literally has just one extra instruction, which is storing the result in the first branch of the if-statement (wherease the ternary just stores the result at the end of the comparison). So, ternaries only execute the branch that would be followed according to the evaluation of the argument, just like an if-else statement.
And, because I was curious, I decided to check if a double ternary is equivalent to an if-elif-else. (Spoiler it is). I used this code to test it, same process as above:
public static void main(String[] args) {
int a = 0;
int b = 2;
int c = 3;
int d = a > b ? MyBigClass.VAR_1 : a > c ? MyOtherBigClass.VAR_2 : 0;
// int d;
// if (a > b) {
// d = MyBigClass.VAR_1;
// } else if (a > c) {
// d = MyOtherBigClass.VAR_2;
// } else {
// d = 0;
// }
}
The bytecode generated for if-elif-else:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iconst_2
3: istore_2
4: iconst_3
5: istore_3
6: iload_1
7: iload_2
8: if_icmple 19
11: getstatic #2 // Field MyBigClass.VAR_1:I
14: istore 4
16: goto 35
19: iload_1
20: iload_3
21: if_icmple 32
24: getstatic #3 // Field MyOtherBigClass.VAR_2:I
27: istore 4
29: goto 35
32: iconst_0
33: istore 4
35: return
The bytecode generated for ternary:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iconst_2
3: istore_2
4: iconst_3
5: istore_3
6: iload_1
7: iload_2
8: if_icmple 17
11: getstatic #2 // Field MyBigClass.VAR_1:I
14: goto 29
17: iload_1
18: iload_3
19: if_icmple 28
22: getstatic #3 // Field MyOtherBigClass.VAR_2:I
25: goto 29
28: iconst_0
29: istore 4
31: return
What Javac Source Code Actually Does
For the bold the brave and the few
I decided to look at the source for javac... It took awhile, but with a little help from their hitchhiker's guide to javac, I was able to find the one line that definitively determines what happens. Check it out (Line 914): https://hg.openjdk.java.net/jdk9/jdk9/langtools/file/65bfdabaab9c/src/jdk.compiler/share/classes/com/sun/tools/javac/parser/JavacParser.java
Do you see that? Let me clarify this a bit, lines 905-918 say this:
/** Expression1Rest = ["?" Expression ":" Expression1]
*/
JCExpression term1Rest(JCExpression t) {
if (token.kind == QUES) {
int pos = token.pos;
nextToken();
JCExpression t1 = term();
accept(COLON);
JCExpression t2 = term1();
return F.at(pos).Conditional(t, t1, t2);
} else {
return t;
}
}
The comment tells us this is what they use for parsing ternary expressions, and if we look at what it returns, it returns a conditional where t is the expression being evaluated, t1 is the first branch, and t2 is the second branch. Let's take a look at Conditional just to be sure. It looks like Conditional is being called from F, which if we dig a little deeper we can find out is the TreeMaker, what is a tree maker you may ask? Well, it's specifically an Abstract Syntax Tree which is often used as an intermediate representation of the code being parsed (check it out here https://en.wikipedia.org/wiki/Abstract_syntax_tree). Anyways, if we look inside that file (https://hg.openjdk.java.net/jdk9/jdk9/langtools/file/65bfdabaab9c/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/TreeMaker.java) we can see at lines 306-313 this:
public JCConditional Conditional(JCExpression cond,
JCExpression thenpart,
JCExpression elsepart)
{
JCConditional tree = new JCConditional(cond, thenpart, elsepart);
tree.pos = pos;
return tree;
}
Which further confirms exactly what we thought, that a ternary expression is compiled exactly the same as an if-else statement (otherwise known as a conditional statement) :) I encourage anyone interested to take a look at the hitchhiker's guide (https://openjdk.java.net/groups/compiler/doc/hhgtjavac/index.html) and the code, it's actually really interesting to see how even a commercial grade compiler follows a lot of the principle things that you learn about in your standard compiler course at college.
The Java compiler literally replaces it with an if else block. I remember reading about this in a book during Programming Fundamentals I or II.
return isValid ? foo : bar;
literally precompiles to
if(isValid) {
return foo;
} else {
return bar;
}
which is then compiled as normal.
I was making some tests with numeric conversions and casts in Java and I found this strange behaviour (for me)
class Test {
public static void main(String[] args) {
//int y = 100000000000000; //does not compile
int x = 100000 * 1000000000; //compile (why?)
System.out.println(x); //x is 276447232
}
}
Basically x and y should be the same number: why does it compile?
Integer overflow goes undetected in Java, that's why the multiplication works fine. However, the literal you were stating was too large and thus is a compiler error.
I guess while the vast majority of Java compilers will precompute that value at compilation time that is not required by the JLS. Thus it cannot be an error, since then different compilers may compile a piece of code or yield errors – something that isn't so nice.
The Sun Java compiler actually performs the calculation as the disassembly shows:
Compiled from "x.java"
class x extends java.lang.Object{
x();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: ldc #2; //int 276447232
2: istore_1
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: iload_1
7: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
10: return
The important thing to note here is that for all intents and purposes the result must be the same as if it were computed during runtime. Therefore no compiler error can occur here.
Java deals with overflowing an integer not by an exception but by instead flipping over to negative values and continuing upward.
As an example, here's this code snippet:
int x = Integer.MAX_VALUE + 1;
System.out.println(x);
Java deals with it the best it can. That snippet outputs:
-2147483648
Which is the value of Integer.MIN_VALUE. You just have to be careful when you are dealing with really big numbers. That's why Java has a BigInteger class to deal with arbitrarily big numbers that go beyond the limit of integers.
This isn't meant to be subjective, I am looking for reasons based on resource utilisation, compiler performance, GC performance etc. rather than elegance. Oh, and the position of brackets doesn't count, so no stylistic comments please.
Take the following loop;
Integer total = new Integer(0);
Integer i;
for (String str : string_list)
{
i = Integer.parse(str);
total += i;
}
versus...
Integer total = 0;
for (String str : string_list)
{
Integer i = Integer.parse(str);
total += i;
}
In the first one i is function scoped whereas in the second it is scoped in the loop. I have always thought (believed) that the first one would be more efficient because it just references an existing variable already allocated on the stack, whereas the second one would be pushing and popping i each iteration of the loop.
There are quite a lot of other cases where I tend to scope variables more broadly than perhaps necessary so I thought I would ask here to clear up a gap in my knowledge. Also notice that assignment of the variable on initialisation either involving the new operator or not. Do any of these sorts of semi-stylistic semi-optimisations make any difference at all?
The second one is what I would prefer. There is no functional difference other than the scoping.
Setting the same variable in each iteration makes no difference because Integer is an immutable class. Now, if you were modifying an object instead of creating a new one each time, then there would be a difference.
And as a side note, in this code you should be using int and Integer.parseInt() rather than Integer and Integer.parse(). You're introducing quite a bit of unnecessary boxing and unboxing.
Edit: It's been a while since I mucked around in bytecode, so I thought I'd get my hands dirty again.
Here's the test class I compiled:
class ScopeTest {
public void outside(String[] args) {
Integer total = 0;
Integer i;
for (String str : args)
{
i = Integer.valueOf(str);
total += i;
}
}
public void inside(String[] args) {
Integer total = 0;
for (String str : args)
{
Integer i = Integer.valueOf(str);
total += i;
}
}
}
Bytecode output (retrieved with javap -c ScopeTest after compiling):
Compiled from "ScopeTest.java"
class ScopeTest extends java.lang.Object{
ScopeTest();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public void outside(java.lang.String[]);
Code:
0: iconst_0
1: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_2
5: aload_1
6: astore 4
8: aload 4
10: arraylength
11: istore 5
13: iconst_0
14: istore 6
16: iload 6
18: iload 5
20: if_icmpge 55
23: aload 4
25: iload 6
27: aaload
28: astore 7
30: aload 7
32: invokestatic #3; //Method java/lang/Integer.valueOf:(Ljava/lang/String;)Ljava/lang/Integer;
35: astore_3
36: aload_2
37: invokevirtual #4; //Method java/lang/Integer.intValue:()I
40: aload_3
41: invokevirtual #4; //Method java/lang/Integer.intValue:()I
44: iadd
45: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
48: astore_2
49: iinc 6, 1
52: goto 16
55: return
public void inside(java.lang.String[]);
Code:
0: iconst_0
1: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
4: astore_2
5: aload_1
6: astore_3
7: aload_3
8: arraylength
9: istore 4
11: iconst_0
12: istore 5
14: iload 5
16: iload 4
18: if_icmpge 54
21: aload_3
22: iload 5
24: aaload
25: astore 6
27: aload 6
29: invokestatic #3; //Method java/lang/Integer.valueOf:(Ljava/lang/String;)Ljava/lang/Integer;
32: astore 7
34: aload_2
35: invokevirtual #4; //Method java/lang/Integer.intValue:()I
38: aload 7
40: invokevirtual #4; //Method java/lang/Integer.intValue:()I
43: iadd
44: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
47: astore_2
48: iinc 5, 1
51: goto 14
54: return
}
Contrary to my expectations, there was one difference between the two: in outside(), the variable i still took up a register even though it was omitted from the actual code (note that all the iload and istore instructions point one register higher).
The JIT compiler should make short work of this difference, but still you can see that limiting scope is a good practice.
(And with regards to my earlier side note, you can see that to add two Integer objects, Java must unbox both with intValue, add them, and then create a new Integer with valueOf. Don't do this unless absolutely necessary, because it's senseless and slower.)
The second one is far better because the first style is should only be used in C code as its mandatory. Java allows for inline declarations to minimize the scope of variables and you should take advantage of that. But you code can be further improved:
int total = 0;
for (String str: stringList) {
try {
total += Integer.valueOf(str);
} catch(NumberFormationException nfe) {
// more code to deal with the error
}
}
That follows the Java code style convention. Read the full guide here:
http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
It makes no significant difference apart from on the last iteration, when the reference is cleared quicker in the second example (and that would be my preference - not so much for that reason, but clarity.)
Keep the scope to the minimum possible. The hotspot VM does escape analysis to determine when references are no longer accessible, and on the basis of this allocates some objects on the stack rather than on the heap. Keeping scope as small as possible aids this process.
I would ask why you're using Integer instead of a simple int...or perhaps it's just by way of example?
The second is far better. Scoping variables as narrowly as possible makes the code far easier to read and maintain, which are much more important overall than the performance differences between these examples, which are trivial and easily optimized away.
Neither. Integer.valueOf(0); will use a reference to a cached 0. :)
Well, in this case, you're instantiating an Integer primitive every single time you say i = Integer.parseInt(str) (where i is an Integer), so (unless Java knows how to optimize it), both cases are almost equally inefficient. Consider using int instead:
int total = 0;
for (String str : string_list)
{
int i = Integer.parseInt(str);
total += i;
}
Now we're back to the question of whether to put the int declaration on the inside or outside. Assuming the Java compiler has a lick of decent optimization, I'd say it doesn't matter. Efficiency aside, it is considered good practice to declare variables as close as possible to their use.
The second one is the preferable of the two for readability, maintainability, and efficiency.
All three of these goals are achieved because you are succinctly explaining what you are doing and how your variables are being used. You are explaining this clearly to both developers and the compiler. When the variable i is defined in the for block everyone knows that it is safe to ignore it outside of the block and that the value is only valid for this iteration of the block. This will lead the to the Garbage Collector being able to be able to easily mark this memory to be freed.
I would suggest not using Integer for intermediate values. Accumulate the total as an int and after the loop create the Object or depend on auto-boxing.
Assuming you have positive numbers in your list and you're serious with
I am looking for reasons based on
resource utilisation, compiler
performance, GC performance etc.
rather than elegance.
You should implement it by yourself like:
import java.util.ArrayList;
import java.util.List;
public class Int {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("10");
list.add("20");
int total = 0;
for (String str : list) {
int val = 0;
for (char c : str.toCharArray()) {
val = val * 10 + (int) c - 48;
}
total += val;
}
System.out.print(total);
}
}
The only GC relevant thing would be toCharArray() which could be replaced by another loop using charAt()
The question of what variable scope to use is a readability issue more than anything else. The code is better understood when every variable is restricted to the scope where it is actually used.
Now, if we inspect the technical consequences of using wide/narrow scopes, I believe that there IS a performance/footpring advantage with narrow scopes. Consider the following method, where we have 3 local variables, belonging to one global scope:
private static Random rnd = new Random();
public static void test() {
int x = rnd.nextInt();
System.out.println(x);
int y = rnd.nextInt();
System.out.println(y);
int z = rnd.nextInt();
System.out.println(z);
}
If you diassemble this code (using javap -c -verbose {class name} for example), you will see that the compiler reserves 3 slots for local variables in the stack frame structure of the test() method.
Now, suppose that we add some artificial scopes:
public static void test() {
{
int x = rnd.nextInt();
System.out.println(x);
}
{
int y = rnd.nextInt();
System.out.println(y);
}
{
int z = rnd.nextInt();
System.out.println(z);
}
}
If you diassemble the code now, you will notice that the compiler reserves only 1 slot for local variables. Since the scopes are completely independent, each time x,y or z are used, the same slot #0 is used.
What does it mean?
1) Narrow scopes save stack space
2) If we are dealing with object variables, it means that the objects may become unreachable faster, therefore are eligible for GC sooner than otherwise.
Again,note that these 2 "advantages" are really minor, and the readability concern should be by far the most important concern.
Second one since you want to keep the scope of your variables as "inner" as possible. The advantage of smaller scope is less chance for collision. In your example, there's only a few lines so the advantage might not be so obvious. But if it's larger, having the smaller-scope variables definitely is more beneficial. If someone else later has to look at the code, they would have to scan all the way back to right outside the method definition to know what i is. The argument is not much different than that of why we want to avoid global variable.
This question already has answers here:
Is there a performance difference between a for loop and a for-each loop?
(16 answers)
Closed 5 years ago.
In Java, is it faster to iterate through an array the old-fashioned way,
for (int i = 0; i < a.length; i++)
f(a[i]);
Or using the more concise form,
for (Foo foo : a)
f(foo);
For an ArrayList, is the answer the same?
Of course for the vast bulk of application code, the answer is it makes no discernible difference so the more concise form should be used for readability. However the context I'm looking at is heavy duty technical computation, with operations that must be performed billions of times, so even a tiny speed difference could end up being significant.
If you're looping through an array, it shouldn't matter - the enhanced for loop uses array accesses anyway.
For example, consider this code:
public static void main(String[] args)
{
for (String x : args)
{
System.out.println(x);
}
}
When decompiled with javap -c Test we get (for the main method):
public static void main(java.lang.String[]);
Code:
0: aload_0
1: astore_1
2: aload_1
3: arraylength
4: istore_2
5: iconst_0
6: istore_3
7: iload_3
8: iload_2
9: if_icmpge 31
12: aload_1
13: iload_3
14: aaload
15: astore 4
17: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
20: aload 4
22: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
25: iinc 3, 1
28: goto 7
31: return
Now change it to use an explicit array access:
public static void main(String[] args)
{
for (int i = 0; i < args.length; i++)
{
System.out.println(args[i]);
}
}
This decompiles to:
public static void main(java.lang.String[]);
Code:
0: iconst_0
1: istore_1
2: iload_1
3: aload_0
4: arraylength
5: if_icmpge 23
8: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
11: aload_0
12: iload_1
13: aaload
14: invokevirtual #3; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
17: iinc 1, 1
20: goto 2
23: return
There's a bit more setup code in the enhanced for loop, but they're basically doing the same thing. No iterators are involved. Furthermore, I'd expect them to get JITted to even more similar code.
Suggestion: if you really think it might make a significant difference (which it would only ever do if the body of the loop is absolutely miniscule) then you should benchmark it with your real application. That's the only situation which matters.
This falls squarely in the arena of micro-optimization. It really doesn't matter. Stylistically I always prefer the second because it's more concise, unless you need the loop counter for something else. And that's far more important than this kind of micro-optimization: readability.
That being said, For an ArrayList there won't be much difference but a LinkedList will be much more efficient with the second.
Measure it. The answer on all performance-questions can depend on VM-version, processor, memory-speed, caches etc. So you have to measure it for your particular platform.
Personally I would prefer the second variant, because the intention is more clear. If performance becomes a problem I can optimize it later anyways - if that code really is important for the performance of the whole application.
For a LinkedList:
for(ClassOfElement element : listOfElements) {
System.out.println(element.getValue());
}
It was answered before:
Is there a performance difference between a for loop and a for-each loop?
On an array, or RandomAccess collection you can get a tiny increase in speed by doing:
List<Object> list = new ArrayList<Object>();
for (int i=0, d=list.size(); i<d; i++) {
something(list.get(i));
}
But I wouldn't worry in general. Optimisations like this wont make more than 0.1% difference to your code. Try invoking java with -prof to see where your code is actually spending its time.
Even faster is to use the ParallelArray of the fork-join framework (if you have large enough dataset).