A colleague and I just had an interesting discussion:
What is the difference between For
and For Each
?
In code I already know how it works, but what about behind? What is really recommended? In which cases should we use one and in which the other?
Taking into account speed, memory, etc...
Here I leave you a quite interesting reference , but I think that the thing could be clarified more.
The main difference, in most languages, is that a
for
iterates over things that don't have to exist , and grants us the access order; for its part, anfor-each
iterates over things that must necessarily exist . In addition, we do not guarantee the order in which they are accessed.in PHP
As you can see, the would
for
traverse the range of values0, 1, 2, 3, 4
, but none of them exist before thefor
. You don't loop through a list of anything; the values are generated on the fly, and it is checked whether or not they meet the condition.In this case, the content of an array is iterated over . This arrangement must already exist . It is not auto-generated ; values are taken from a previously existing list .
Just subtly different from the previous one. The values, likewise, are taken from an already existing list .
C++
Virtually identical to PHP . A value is auto-generated, and it is checked that it meets a certain condition. This value does not have to exist outside the
for
.A container is traversed , from its first element to its last.
Well, the case of C++ is different . A certain function of an object is called, and the resulting object is updated as long as a certain condition is met. Since the functions involved are user-generated...well, we really have no idea if the values existed before the
for
. It can be considered an extreme case of polyvalence.However, this form was introduced to make containers easier to use; so, in its original conception , we can conclude that, like PHP , it loops through a list of elements that existed before the
for
.Trends
It seems that the trend is towards the
for-each
C++ language form; make calls to auxiliary functions that are the ones that really provide us with the real value to be treated.This way of working is very versatile , but it implies a certain extra cost (as a rule, especially in non-compiled languages, a function call is more expensive than calling an operator provided by the language).
Efficiency in its use with containers
In the case of wanting to iterate over the data in a container, in non-compiled languages, the
for-each
.This is already off topic, but roughly , in interpreted languages, objects or dictionaries or whatever they are called are usually implemented through trees or through hash tables (less frequent).
Being implemented using trees, accessing from one node to the next is relatively easy ; simply accessing a pointer is sufficient , which is little short of immediate (the form
for-each
does not guarantee the order in which the various values will be visited).However, accessing the element
Contenedor[5]
entails traversing the tree, from its root, comparing the keys until finding the one sought. Much slower than the previous case.Billet "grandfather onion", notice:
Each language has its variant, but, if we go back to the original concept, the for loop was a loop with a certain number (before starting) of iterations:
If you didn't know the number of iterations beforehand, then you had to use a while loop:
This was so much assumed that in languages like Pascal or Modula-2, the condition was set at the start and was immutable. For example, the following code:
It did not produce an infinite loop, but instead executed 5 times, even though n was 10 after the last iteration, because the condition was checked against the value of n at the beginning of the loop.
But then C came along and created a "bastard" for, mixing for and while:
The syntax of this for doesn't even force you to use a counter or have code in the body of the loop:
So we have that today there is no difference between while and for
The forEach loop is almost a return to origins: as long as you don't use a
break
, the number of iterations is the number of elements in the collection you are looping through. But this loop only provides a simpler syntax, the functionality is even less than that of the "classic" for loop since we don't know the index of the element and therefore we can't do something as basic as delete it or replace it with another one in the collection that we are touring Example in Java: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:
and that it cannot be stopped either, so other functions have been created such as some, filter, find... that do not require going through the entire collection.
End of 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, 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) , so the performance will be quite similar.
I think that depending on the need you will use one or the other.
for-each
is more comfortable as far as syntax is concerned and his reading is simple and clear. What is an advantagefor
is much more ambiguous in that sense and adds a little more complexity and you are more likely to get some parameter wrong.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#