Foreach performs operations on Array replicas (by copying arrays), while operations are performed by moving internal indicators of the array. Generally, it is logically considered that, while should be faster than foreach (because foreach first copies the array when starting execution, while directly moves the internal indicator .), But the result is just the opposite.
If the array "read" operation is performed in a loop, foreach is faster than while:
Copy codeThe Code is as follows:
Foreach ($ array as $ value ){
Echo $ value;
}
While (list ($ key) = each ($ array )){
Echo $ array [$ key];
}
When the array "write" operation is performed in a loop, while is faster than foreach:
Copy codeThe Code is as follows:
Foreach ($ array as $ key => $ value ){
Echo $ array [$ key] = $ value .'...';
}
While (list ($ key) = each ($ array )){
$ Array [$ key] = $ array [$ key]. '...';
}
Conclusion: foreach is generally considered to be slower than while when it involves value replication, but in fact, if it is just to read the array in a loop, foreach is very
This is because PHP adopts the replication mechanism of "reference count, write copy". That is to say, even if a variable is copied in PHP, the initial form is basically
It is still the form of reference. Only when the content of the variable changes will the real replication occur. The reason for doing so is to save memory consumption and improve
Replication efficiency. In this case, foreach's efficient read operations are not difficult to understand. In addition, since foreach is not suitable for Array write operations, we can get a knot
In most cases, code for array write operations like foreach ($ array as $ key => $ value) should be replaced with while (list ($ key) =
Each ($ array )). The speed difference produced by these skills may not be obvious in small projects, but in large projects like frameworks, a single request may involve a few
Hundreds of thousands of array loop operations, the difference will be significantly magnified.