PHP for 循环与带范围的 foreach
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13929468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP for loop vs. foreach with range
提问by Emil Aspman
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
Edit: Did a benchmark and the last one was almost 6 times faster.
编辑:做了一个基准测试,最后一个几乎快了 6 倍。
采纳答案by Carlos
Traditional forloop 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.
传统for循环比foreach+快range。第一个只使用整数比较和递增,而最后一个必须创建一个(可能很大)数组,然后通过移动内部数组光标并检查是否到达末尾来提取每个元素。
If you execute this you can see that plain foris twice faster than foreach+ range:
如果你执行这个,你可以看到 plainfor比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;
It is better to use traditional foras 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).
for在需要迭代给定次数的情况下,最好使用传统作为习惯,但在一天结束时,在大多数情况下您不会看到显着的性能改进(考虑到上面的示例迭代了 100k 次,如果减少迭代次数,差异会更小)。
回答by Mark Baker
If it's that critical,
如果真的那么关键
for($i = 0; $i < 1000; ++$i) {}
is faster than
比
for($i = 0; $i < 1000; $i++) {}
but you'll not really notice much difference over just 1000 iterations
但在 1000 次迭代中你不会真正注意到太大的差异
Is it really so essential to micro-optimize.... and if so, why can't you simply set up some test runs to compare the different options yourself
微优化真的那么重要吗....如果是这样,为什么你不能简单地设置一些测试运行来自己比较不同的选项
回答by echo_Me
Foreachis great for iterating through arrays that use keys and values.
Foreach非常适合遍历使用键和值的数组。
For example, if I had an array called 'User':
例如,如果我有一个名为“User”的数组:
$User = array(
'name' => 'Bob',
'email' => '[email protected]',
'age' => 200
);
I could iterate through that very easily and still make use of the keys:
我可以非常轻松地遍历它并仍然使用这些键:
foreach ($User as $key => $value) {
echo $key.' is '.$value.'<br />';
}
This would print out:
这将打印出:
name is Bob
email is [email protected]
age is 200
With forloops, it's more difficult to retain the use of the keys.
对于for循环,保留密钥的使用更加困难。
When you're using object-oriented practice in PHP, you'll find that you'll be using foreachalmost entirely, with forloops only for numerical or list-based things. foreachalso prevents you from having to use count($array)to find the total number of elements in the array.
当您在 PHP 中使用面向对象的实践时,您会发现您将foreach几乎完全使用for循环,仅针对数字或基于列表的事物使用循环。foreach还可以防止您不得不使用count($array)查找数组中的元素总数。
回答by Narf
In this particular case (with range()and not an array passed from another scope) - foreach()will be faster.
for()would beat it in almost any other case.
在这种特殊情况下(有range()而不是从另一个范围传递的数组) -foreach()会更快。
for()几乎在任何其他情况下都会击败它。
回答by rOcKiNg RhO
Foreach is great for iterating through arrays that use keys and values. With for loops, it's more difficult to retain the use of the keys. http://www.c-sharpcorner.com/interviews/answer/2147/this may be helpful
Foreach 非常适合遍历使用键和值的数组。对于 for 循环,保留键的使用更加困难。 http://www.c-sharpcorner.com/interviews/answer/2147/这可能会有所帮助
回答by Sivagopal Manpragada
comparing execution speed of some php functions
比较一些php函数的执行速度
for loop took
for 循环
for()loop using count()took 20.86401 ms
for()循环using count()耗时 20.86401 毫秒
for()loop Not using count()took 7.09796 ms
for()循环Not using count()耗时 7.09796 毫秒
using count() means:
for ($i = 1; $i < count($myarr); ++ $i) {..
使用 count() 意味着:
for ($i = 1; $i < count($myarr); ++ $i) {..
where as foreach() loop:
其中 foreach() 循环:
foreach()took 11.16920 ms
foreach()花了 11.16920 毫秒
foreach()with KEY took 12.35318 ms
foreach()使用 KEY 耗时 12.35318 毫秒
these both are done on same array and their respective execution time is shown both forand foreachare language constructs and their execution speed will be more so you cannot notice much more difference unless you are using them on an array with thousands of records.
这两个都是在同一个数组上完成的,它们各自的执行时间都显示出来,for并且foreach都是语言结构,它们的执行速度会更快,因此除非您在具有数千条记录的数组上使用它们,否则您不会注意到更多差异。

