php for vs foreach vs while 在php中迭代数组更快
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1852242/
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
for vs foreach vs while which is faster for iterating through arrays in php
提问by streetparade
which one is the fastest for iterating through arrays in php? or does another exist which is also faster for iterating through arrays?
哪个是在 php 中迭代数组最快的?或者是否存在另一个也可以更快地迭代数组?
回答by Pascal MARTIN
Even if there is any kind of difference, that difference will be so small it won't matter at all.
就算有什么差别,那个差别也小到根本不重要。
If you have, say, one query to the database, it'll take so long compared to the loop iterating over the results that the eternal debate of forvs foreachvs whilewill not change a thing -- at least if you have a reasonable amount of data.
例如,如果您对数据库进行了一次查询,那么与迭代结果的循环相比,它会花费很长时间,以至于forvs foreachvs的永恒争论while不会改变任何事情——至少如果您有合理数量的数据.
So, use :
所以,使用:
- whatever you like
- whatever fits your programming standard
- whatever is best suited for your code/application
- 随你喜欢
- 任何符合您的编程标准的
- 什么最适合您的代码/应用程序
There will be plenty of other things you could/should optimize before thinking about that kind of micro-optimization.
在考虑这种微优化之前,您可以/应该优化许多其他事情。
And if you really want some numbers (even if it's just for fun), you can make some benchmark and see the results in practice.
如果你真的想要一些数字(即使只是为了好玩),你可以做一些基准测试并在实践中查看结果。
回答by Shawn Wernig
For me I pick my loop based on this:
对我来说,我根据这个选择我的循环:
foreach
Use when iterating through an array whose length is (or can be) unknown.
在迭代长度未知(或可能未知)的数组时使用。
for
Use when iterating through an array whose length is set, or, when you need a counter.
在迭代长度已设置的数组时使用,或者当您需要计数器时使用。
while
Use when you're iterating through an array with the express purpose of finding, or triggering a certain flag.
当您以查找或触发某个标志的明确目的遍历数组时使用。
Now it's true, you can use a FOR loop like a FOREACH loop, by using count($array)... so ultimately it comes down to your personal preference/style.
现在是真的,你可以像 FOREACH 循环一样使用 FOR 循环,通过使用 count($array) ......所以最终它归结为你的个人喜好/风格。
回答by fyrye
In general there is no applicable speed differences between the three functions.
一般来说,这三个功能之间没有适用的速度差异。
To provide benchmark results to demonstrate the efficiency of varying methods used to iterate over an array from 1 to 10,000.
提供基准测试结果以证明用于从1 to 10,000.
Benchmark results of varying PHP versions: https://3v4l.org/a3Jn4
不同 PHP 版本的基准测试结果:https: //3v4l.org/a3Jn4
while $i++: 0.00077605247497559 sec
for $i++: 0.00073003768920898 sec
foreach: 0.0004420280456543 sec
while current, next: 0.024288892745972 sec
while reset, next: 0.012929201126099 sec
do while next: 0.011449098587036 sec //added after terminal benchmark
while array_shift: 0.36452603340149 sec
while array_pop: 0.013902902603149 sec
Takes into consideration individual calls for countwith whileand for
考虑到count与while和for
$values = range(1, 10000);
$l = count($values);
$i = 0;
while($i<$l){
$i++;
}
$l = count($values);
for($i=0;$i<$l;$i++){
}
foreach($values as $val){
}
The below examples using while, demonstrate how it would be used less efficiently during iteration.
下面使用while, 的示例演示了如何在迭代过程中降低使用效率。
When functionally iterating over an array and maintaining the current position; whilebecomes much less efficient, as next()and current()is called during the iteration.
在功能上迭代数组并保持当前位置时;while变得低效,因为next()和current()在迭代期间被调用。
while($val = current($values)){
next($values);
}
If the current positioning of the array is not important, you can call reset()or current()prior to iteration.
如果数组的当前定位不重要,可以在迭代之前调用reset()或current()。
$value = reset($values);
while ($value) {
$value = next($values);
}
do ... whileis an alternative syntax that can be used, also in conjunction with calling reset()or current()prior to iteration and by moving the next()call to the end of the iteration.
do ... while是一种可以使用的替代语法,也可以与调用结合使用reset()或current()在迭代之前以及通过将next()调用移动到迭代结束。
$value = current($values);
do{
}while($value = next($values));
array_shiftcan also be called during the iteration, but that negatively impacts performance greatly, due to array_shiftre-indexing the array each time it is called.
array_shift也可以在迭代期间调用,但由于array_shift每次调用时都会重新索引数组,这会对性能产生很大的负面影响。
while($values){
array_shift($values);
}
Alternatively array_reversecan be called prior to iteration, in conjunction with calling array_pop. This will avoid the impact from re-indexing when calling array_shift.
或者array_reverse可以在迭代之前调用,结合调用array_pop. 这将避免调用时重新索引的影响array_shift。
$values = array_reverse($values);
while($values) {
array_pop($values);
}
In conclusion, the speed of while, for, and foreachshould not be the question, but rather what is done within them to maintain positioning of the array.
总之,while、for、 和的速度foreach不应该是问题,而是在它们内部做了什么来保持阵列的定位。
回答by Morg.
Correctly used, while is the fastest, as it can have only one check for every iteration, comparing one $i with another $max variable, and no additional calls before loop (except setting $max) or during loop (except $i++; which is inherently done in any loop statement).
正确使用,while 是最快的,因为它每次迭代只能进行一次检查,将一个 $i 与另一个 $max 变量进行比较,并且在循环之前(设置 $max 除外)或循环期间($i++ 除外;其中本质上是在任何循环语句中完成的)。
When you start misusing it (like while(list..) ) you're better off with foreach of course, as every function call will not be as optimized as the one included in foreach (because that one is pre-optimized).
当您开始滥用它时(例如 while(list..) ),当然最好使用 foreach ,因为每个函数调用都不会像 foreach 中包含的函数调用那样优化(因为它是预先优化的)。
Even then, array_keys() gives you the same usability as foreach, still faster. And beyond that, if you're into 2d-arrays, a home-made 2d_array_keys will enable you to use while all the way in a much faster way then foreach can be used (just try and tell the next foreach within the first foreach, that the last foreach had <2d_array_keys($array)> as keys --- ).
即便如此,array_keys() 仍为您提供与 foreach 相同的可用性,而且速度更快。除此之外,如果您喜欢 2d 数组,自制的 2d_array_keys 将使您能够以更快的方式使用 while,然后可以使用 foreach(尝试并告诉第一个 foreach 中的下一个 foreach,最后一个 foreach 有 <2d_array_keys($array)> 作为键 --- )。
Besides, all questions related to first or last item of a loop using a while($i
此外,所有与循环的第一项或最后一项相关的问题都使用 while($i
And
和
while ($people_care_about_optimization!==true){
echo "there still exists a better way of doing it and there's no reason to use any other one";
}
回答by Julius F
Make a benchmark test.
进行基准测试。
There is no major "performance" difference, because the differences are located inside the logic.
没有主要的“性能”差异,因为差异位于逻辑内部。
- You use foreach for array iteration, without integers as keys.
- You use for for array iteration with integers as keys.
- etc.
- 您使用 foreach 进行数组迭代,不使用整数作为键。
- 您用于以整数为键的数组迭代。
- 等等。
回答by Valerio Bozz
Remember that prefetching a lot of mysqli_resultinto a comfortable array can raise the question whether it is better to use for/foreach/whileto cycle that array, but it's the wrong question about a bad solution that waste a lot of RAM.
请记住,预取了大量的mysqli_result成舒适的阵列可以提出这样的问题是否是最好使用for/ foreach/while循环数组,但它是关于一个糟糕的解决方案,浪费了大量的内存错误的问题。
So do not prefere this:
所以不要喜欢这个:
function funny_query_results($query) {
$results = $GLOBALS['mysqli']->query($query);
$rows = [];
while( $row = $results->fetch_object() ) {
$rows[] = $results;
}
return $rows;
}
$rows = funny_query_results("SELECT ...");
foreach($rows as $row) { // Uh... What should I use? foreach VS for VS while?
echo $row->something;
}
The direct way getting one-by-one every mysql_resultin a simple whileis a lot more optimized:
mysql_result在简单中逐一获取的直接方法while更加优化:
$results = $mysqli->query("SELECT ...");
while( $row = $results->fetch_object() ) {
echo $row->something;
}


