Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach vs common for loop

Tags:

java

foreach

I just started learning Java and the first thing I came across is the foreach loop, not knowing the way it works the first thing I did was:

int[] array = new int [10];
for (int i: array){
    i = 1;
}

And obviously failed to assign 1 to every element of the array. Then I added System.out.print(i); (after i = 1;) to the body of the loop and saw that the output of the screen was 1111111111 but since doing something with i inside the loop is valid that most likely i is a copy of every element of the array, ain't it? (first questions)

If the above is true doesn't this mean that the foreach loop is much slower then the common for loop since it involves making copies of each element of the array? Or since Java doesn't have pointers and pointer arithmetic, the oprator[] may be designed in some other "badly" fashion that copying every element is actually faster?

And if the above assumptions are true, why one would use an obviously slower foreach loop instead of a common forloop?

In short the questions:

  • Is i the copy of each element of the array? If not what is it then?

  • Isn't the foreach loop slower then the common one? If not, how "badly" is then operator[] designed?

  • There is nothing more except readability to win in a foreach loop?

like image 507
Alexandru Barbarosie Avatar asked Sep 13 '13 14:09

Alexandru Barbarosie


People also ask

Is forEach better than for loop?

This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

What is the difference between foreach loop and for loop?

The for loop is a control structure for specifying iteration that allows code to be repeatedly executed. The foreach loop is a control structure for traversing items in an array or a collection. A for loop can be used to retrieve a particular set of elements.

Is forEach more efficient than for?

forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm.

What is the advantage of using forEach over traditional for loop?

The forEach() method provides several advantages over the traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of a regular stream. Since you are operating on stream, it also allows you to filter and map elements.


Video Answer


3 Answers

In the code

for (int i: array){

You declare a variable i that on each loop iteration gets the value of the next element in the array, it isn't a reference to that element.

In

i = 1;

you assign a new value to the variable, not to the element in the array.

You cannot set the values of array elements with a foreach loop directly. Use a normal for loop for that

for (int i = 0; i < array.length; i++) {
    array[i] = ...; // some value
}

In the above example, you are using the declared variable i as an index to the element in the array.

array[i] 

is accessing the element itself whose value you can modify.


Ans obviously failed to assign 1 to every element of the array. The I added System.out.print(i); to the body of the loop and saw that the output of the screen was 1111111111 but since doing something with i inside the loop is valid that most likely i is a copy of every element of the array, ain't it? (first questions)

You must have put the System.out.print(i) after the i = 1, otherwise you would get 0000000.

If the above is true doesn't this mean that the foreach loop is much slower then the common for loop since it involves making copies of each element of the array? Or since Java doesn't have pointers and pointer arithmetic, the oprator[] may be designed in some other "badly" fashion that copying every element is actually faster?

Have a look here to see how the foreach loop works. For arrays,

for (int i: array){
    i = 1;
}

is equivalent to

for (int index = 0; index < array.length; index++) {
    int i = array[index];
    i = 1;
}

So it isn't slower. You're doing one more primitive creation on the stack.

It depends on the implementation. For arrays, it's not slower in any way. It just serves different purposes.

why one would use an obviously slower foreach loop instead of a common forloop?

One reason is for readability. Another is when you don't care about changing the element references of the array, but using the current references.

Take a reference type example

public class Foo {
    public int a;
}

Foo[] array = new Foo[3];
for (int i = 0; i < array.length; i++) {
    array[i] = new Foo();
    array[i].a = i * 17;
}

for (Foo foo : array) {
    foo.a = 0; // sets the value of `a` in each Foo object
    foo = new Foo(); // create new Foo object, but doesn't replace the one in the array
}

With primitive types such a thing doesn't work.

for (int index = 0; index < array.length; index++) { 
    int i = array[index];
    i = 1; // doesn't change array[index]
}
like image 96
Sotirios Delimanolis Avatar answered Sep 20 '22 00:09

Sotirios Delimanolis


From Item 46 in Effective Java by Joshua Bloch :

The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

Advantages

  1. Readability
  2. It increases the abstraction level - instead of having to express the low-level details of how to loop around a list or array (with an index or iterator), the developer simply states that they want to loop and the language takes care of the rest.

Disadvantage:

Cannot access the index or to remove an item.

To sum up,

the enhanced for loop offers

  1. A concise higher level syntax to loop over a list or array which

    1.1 improves clarity

    1.2 readability.

    However, it misses : allowing to access the index loop or to remove an item.

like image 39
JNL Avatar answered Sep 20 '22 00:09

JNL


Setting the values by reference didn't work because int is a primitive type. For any kind of Object[] it would work. Making a copy of a primitive type is very fast, and will be done by the processor many times without your realising.

The foreach loop is more readable, but it's also more writeable. A common programmer error is:

for (int i = 0; i < 10; i++)
{
    for(int j = 0; j < 10; i++) //oops, incrementing wrong variable!
    {
        //this will not execute as expected
    }
}

It's impossible to make this error using a foreach loop.

like image 32
MikeFHay Avatar answered Sep 18 '22 00:09

MikeFHay