Difference between FOR and FOR EACH [closed]


A colleague and I have just had an interesting debate:

What is the difference between For and For Each ?

I already know how it works in code, but from behind? Really what is the most advisable? In which cases should we use one and in which the other?

Taking into account speed, memory, etc ...

Here I leave a reference quite interesting, but I think you could clarify the thing more.

asked by GDP 15.09.2017 в 12:30

3 answers


The main difference, in most languages, is that a for iterates over things that do not have to exist , and guarantees the order of access; On the other hand, a for-each iterates about things that, obligatorily, must exist . In addition, does not guarantee us the order in which it is accessed.


for( $a = 0; $a < 5; $a++ ) {

As you can see, the for would go through the range of values 0, 1, 2, 3, 4 , but none of them exist before the own for . You do not go through a list of anything; the values are generated on the fly, and it is checked whether or not they meet the condition.

foreach( $arr as $v ) {

In this case, iterates over the content of an array . Said array must exist before . It does not go auto-generating ; the values are taken from a previously existing list .

foreach( $arr as $k => $v ) {

Just subtly different from the previous one. Values, likewise, are taken from an existing list .

C ++

for( idx = 0; idx < 5; ++idx ) {

Practically identical to PHP . A value is self-generated, and it is verified that it meets a certain condition. This value does not have to exist outside of for .

for( idx: container ) {

A container is traversed, from its first element to the last one.

Well, the case of C ++ is different . A certain function of an object is called, and the resulting object is updated while a certain condition is met. As the functions involved are generated by the user ... because in fact we have no idea of whether the values existed prior to the for . It can be considered an extreme case of polyvalence.

However, this form was introduced to facilitate the use of containers; so, in its original conception, we can conclude that, like PHP , a list of elements that previously existed is traversed at for .


It seems that the trend is towards the for-each form of the C ++ language; make calls to auxiliary functions that are what really give us the real value to deal with.

This way of working is very versatile , but it implies a certain extra cost (as a rule, especially in non-compiled languages, a call to a function is more expensive to call an operator provided by the language).

Efficiency in its use with containers

In the case of wanting to iterate on the data of a container, in non-compiled languages, the form for-each is usually faster.

This is already out of the issue, but, rough-mode , in interpreted languages, objects or dictionaries or as calls are usually implemented by trees or by hash tables (less frequent).

Being implemented by trees, access from one node to the next is relatively easy ; just access a pointer , which is little less than immediate (the for-each does not guarantee the order in which you will visit the different values). p>

However, accessing the Contenedor[5] element involves traversing the tree, from its root, comparing the keys until the search is found. Quite slower than the previous case.

answered by 15.09.2017 / 13:56

Tocho "grandfather chive", notice:

Each language has its variant, but, if we go to the original concept, the for loop was a loop with a certain number (before starting) of iterations:

for i=0 to 30 do

If you did not know the number of iterations in advance, then you had to use, necessarily, a while loop:

while (condición) do

This was so assumed that in languages such as Pascal or Modula-2, the condition was established at the beginning and was immutable. For example, the following code:

for i=1 to n do

It did not produce an infinite loop, but it was executed 5 times, although n was 10 after the last iteration, because the condition was checked with respect to the value of n at the beginning of the loop.

But then C arrived and created a for "bastard", mixing for and while:

for (inicialización; condición; código) {

The syntax of this for does not even force to use a counter or have code in the body of the loop:

for ( ; int elem=pila.pop()!=null; otraPila.push(elem));

So we have that today there is no difference between while and for

The forEach loop is almost a return to the origins: as long as you do not use a break , the number of iterations is the number of elements of the collection you are going through. But this loop only provides a simpler syntax, the functionality is even less than that of the "classic" for loop since we do not know the index of the element and therefore we can not do something as basic as deleting it or replacing it with another one in the collection that we are traveling. Example in Java:

for(Object o: collectionOfObjects) {


In more functional languages, such as javascript or Java 8, they have given it one more twist to favor parallelism and we directly have a function that hides the loop:

myArray.forEach(function (item, index) {...});

and that can not be stopped either, so other functions have been created such as some, filter, find ... that do not force to go through the entire collection.

End of the billet. Now I answer the question which one to use ?:

Use the one that best suits your needs: the forEach loop has a clearer syntax, it does not require declaring an index, and in most cases the compiler will transform it into a classic for loop (in Java using an iterator, for example), with which the performance will be quite similar.

answered by 15.09.2017 в 13:40

I think it depends on the need you will use one or the other.

  • The for-each is more comfortable as far as syntax is concerned and its reading is simple and clear. What is an advantage
  • The for is much more ambiguous in that sense and adds a little more complexity and you have more chance of making mistakes in some parameter.

All this regarding the style but differences in performance ( behind ) I understand that they are practically few if not none , in the eyes of the user.

Another thing is to know what language we are talking about since Javascript to C ++ passing through C #

answered by 15.09.2017 в 12:55