It can be seen that when looping ArrayList, the ordinary for loop takes less time than the foreach loop;
When looping LinkList, the ordinary for loop takes longer than the foreach loop. A lot more.
When I increase the number of loops to one million times, when looping ArrayList, the ordinary for loop is still a little faster than foreach;
But when the ordinary for loop loops LinkList, the program directly Stuck.
Conclusion: Requires data of loop array structureWhen used, it is recommended to use an ordinary for loop, because the for loop uses subscript access, for arrays For structured data, it is better to use subscript access.
When you need circular linked list structure data, be sure not to use an ordinary for loop. This is a bad practice and may cause the system to crash when the amount of data is large. .
Reason: foreach uses an iterator.
Related recommendations:
php Introduction to the difference between foreach and for statement usage_PHP tutorial
The above is the detailed content of Analysis between foreach and normal for loop efficiency. For more information, please follow other related articles on the PHP Chinese website!