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.
In PHP
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
.
Trends
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.