PHP is basically an array language. There are often a lot of array loop operations, mainly in two ways, one is foreach, the other is while, in the end, which is good or bad is always controversial, although I have been aware of this problem for a long time, I have not studied it carefully. I have been ignorant of it until now. In order to save some CPU time in the future, the following is a summary.
PHP is basically an array language. There are often a lot of array loop operations, mainly in two ways, one is foreach, the other is while, in the end, which is good or bad is always controversial, although I have been aware of this problem for a long time, I have not studied it carefully. I have been ignorant of it until now. In order to save some CPU time in the future, the following is a summary.
PHP is basically an array language. There are often a lot of array loop operations, mainly in two ways, one is foreach, the other is while, in the end, which is good or bad is always controversial, although I have been aware of this problem for a long time, I have not studied it in detail. I have been ignorant of it until now. To save some CPU time in the future, I will summarize it as follows:
If the array "read" operation is performed in a loop, foreach is faster than while:
No format to view printed code copied to the clipboard?
Foreach ($ array as $ value ){
Echo $ value;
}
While (list ($ key) = each ($ array )){
Echo $ array [$ key];
}
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:
No format to view printed code copied to the clipboard?
Foreach ($ array as $ key => $ value ){
Echo $ array [$ key] = $ value .'...';
}
While (list ($ key) = each ($ array )){
$ Array [$ key] = $ array [$ key]. '...';
}
Foreach ($ array as $ key => $ value ){
Echo $ array [$ key] = $ value .'...';
}
While (list ($ key) = each ($ array )){
$ Array [$ key] = $ array [$ key]. '...';
}
Conclusion: foreach is usually considered to be slower than while when it involves value replication, but in fact, if it is just a read operation on the array in a loop, foreach is very fast, this is because the replication mechanism adopted by PHP is "reference replication, write copy". In this way, it is not difficult to understand the efficient read operations of foreach.
In addition, since foreach is not suitable for array write operations, we can draw a conclusion that, in most cases, it is similar to foreach ($ array as $ key => $ value) all code in the form should be replaced with while (list ($ key) = each ($ array )).
The speed differences produced by these techniques may not be obvious in small projects, but in large projects like frameworks, a single request may involve hundreds of thousands of array loop operations, the difference is obviously magnified.