What is the best way to loop through an array when you need the index?
Option 1:
int len = array.length;
for (int i = 0; i < len; ++i) {
array[i] = foo(i);
}
Option 2:
for (int i = 0; i < array.length; i++) {
array[i] = foo(i);
}
Or, does it not matter? Or is there a better way to do it? Just to point out the differences: In one case, the length of the array is evaluated as part of the test in the loop, although the compiler should normally optimize that.
++i
any different here from i++
? I definitely prefer ++i
if it is C++ but am not sure for Java.
If the number of iteration is fixed, it is recommended to use for loop. If the number of iteration is not fixed, it is recommended to use while loop. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
Looping in Java These three looping statements are called for, while, and do… while statements. The for and while statements perform the repetition declared in their body zero or more times. If the loop continuation condition is false, it stops execution.
i++
vs ++i
does not matter in this particular case. While C masters will tell you to store array.length in a variable, modern optimizing compilers make that unnecessary in this case as long as the length does not change in the loop. If you're really concerned you can benchmark both, but since .length
doesn't actually need to traverse the entire array each time you'll be OK.
Generally those two methods are equivalent. You should note that in
for (int i = 0 ; i < foo() ; i++) {
...
}
the foo()
is called once before each iteration (as opposed to only once before the first iteration), so you might want to take this into account for more complicated situations by perhaps doing something like
int n = foo();
for (int i = 0 ; i < n ; i++) {
...
}
which is analogous to your Option 1. So I would say Option 1 is certainly the safer of the two, but most of the time it should not make a significant difference which you use.
As for your second question: ++i
first increments your variable and then retrieves it's value, i++
first retrieves the value and then increments. Just try these two pieces of code:
int i = 0;
System.out.println(++i);
------------------------
int i = 0;
System.out.println(i++);
The first prints 1
but the second prints 0
. Of course when ++i
and i++
are alone it makes no difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With