foreach is the operation of an array copy (by copying the arrays), while the while is manipulated by moving the internal indicators of the array, which is generally considered to be faster than foreach (because the foreach first copies the array in the beginning of execution). While the while moves the internal indicator directly. ), but the result is just the opposite.
In the loop is the array "read" operation, then the foreach is faster than the while:
Copy the Code code as follows:
foreach ($array as $value) {
Echo $value;
}
while (list ($key) = each ($array)) {
echo $array [$key];
}
In the loop is an array of "write" operations, while the while is faster than foreach:
Copy the Code code as follows:
foreach ($array as $key = = $value) {
echo $array [$key] = $value. '...';
}
while (list ($key) = each ($array)) {
$array [$key] = $array [$key]. '...';
}
Summary: It is generally assumed that foreach involves a value copy, which must be slower than while, but in fact, if the array is read only in a loop, then foreach is
Fast, this is because PHP uses a replication mechanism that is "reference count, copy-on-write", that is, even if you copy a variable in PHP, the original form basically actually
is still the form of a reference, only if the content of the variable changes, the actual replication will occur, the reason for this is to save the memory consumption purposes, but also improve the
The efficiency of replication. Thus, the efficient read operation of foreach is not difficult to understand. Also, since foreach is not suitable for handling array writes, we can draw a knot
In most cases, the code for array writes similar to the form of foreach ($array as $key + $value) should be replaced by the while (list ($key) =
each ($array)). The speed differences generated by these techniques may not be obvious in small projects, but in large projects like this, a single request can easily involve a few
Hundred thousands of tens of thousands of array loop operation, the difference will be significantly enlarged.
The above describes the Torrentkitty search PHP foreach, while performance comparison, including the Torrentkitty search aspect of the content, I hope the PHP tutorial interested in a friend helpful.