PHP for循环与同系列的foreach [英] PHP for loop vs. foreach with range

查看:110
本文介绍了PHP for循环与同系列的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下这些是对性能和可读性更好?

Which of these would be better for performance and readability?

foreach(range(0,10000) as $i) {} // 3.847 ms

for($i = 0; $i < 10000; ++$i) {} // 0.663 ms

修改:有没有一个标杆,最后一个几乎6倍的速度

Edit: Did a benchmark and the last one was almost 6 times faster.

推荐答案

传统环比的foreach 快+ 范围。第一个只使用整数比较,增加而最后一个人通过移动内部数组指针并检查是否达到最终创建一个(可能很大)阵列,然后提取每个元素。

Traditional for loop is faster than foreach + range. The first one only uses integer comparison and increasing while the last one has to create an (possibly big) array and then extract each element by moving the internal array cursor and checking whether the end is reached.

如果您执行这一点,你可以看到,普通的两倍的速度比的foreach + 范围

If you execute this you can see that plain for is twice faster than foreach + range:

$t0 = microtime(true);
for ($i = 0; $i < 100000; $i++) {
}
echo 'for loop: ' . (microtime(true) - $t0) . ' s', PHP_EOL;

$t0 = microtime(true);
foreach (range(0, 100000) as $i) {
}
echo 'foreach + range loop: ' . (microtime(true) - $t0) . ' s', PHP_EOL;

这是更好地利用传统作为的情况下一种习惯,你需要遍历的给定次数,但在这一天结束时,你将不会看到在大多数情况下大的性能改进(考虑到上述迭代100k的倍的例子中,如果减少迭代的次数,不同的是更小)。

It is better to use traditional for as a habit in the case you need to iterate a given number of times but at the end of the day you won't see big performance improvements in most scenarios (take into account that the example above iterates 100k times, if you reduce the number of iterations, the difference is smaller).

这篇关于PHP for循环与同系列的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆