for与foreach哪个性能更好一些?还是处理不同的数据有各自的优点?希望大神给解答一下.
这类问题,应该StackOverflow上也有了:Performance of FOR vs FOREACH in PHP
得票最高的作者说:“他几乎很少用for”,不过这两者的区别在大多数情况下都是很小的。
My personal opinion is to use what makes sense in the context. Personally I almost never usefor
for array traversal. I use it for other types of iteration, butforeach
is just too easy... The time difference is going to be minimal in most cases.
他提到这个循环(比较差的写法):
for ($i = 0; $i < count($array); $i++) {
是一个很昂贵的循环,因为每次都要调用count(感觉这种写法大家都是避免的)
他还贴了一个对比测试:for foreach foreach中用引用
$a = array();
for ($i = 0; $i < 10000; $i++) {
$a[] = $i;
}
$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds
So if you're modifying the array in the loop, it's several times faster to use references...
15 回答8.2k 阅读
8 回答6k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答1.9k 阅读✓ 已解决
2 回答2.3k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.2k 阅读
对
ArrayList
这样的可使用下标进行随机访问的数据结构,使用下标访问,要比foreach
的方式进行顺序访问,速度要快一些。foreach
这样写法,使用的过程产生一个额外的对象Enumerator
,而且每次访问需要更多的操作,降低性能。foreach
是通过GetEnumerator
获得一个IEnumerator
对象,通过IEnumerator
对象执行MoveNext()
方法和获取Current
属性进行遍历的。由于
Enumerator
中,做了版本检查处理
的工作,所以使用foreach
是线程安全
所以
for
的效率通常来说是高于foreach
的,但话也不能说是绝对。那么如何选择呢?我的建议是,在一些全局的,多线程可以访问的数据结构对象,使用
foreach
。而对本地变量,则使用for
,效率和安全兼顾!更新:刚刚查了下资料,发现对于10W级以上的数组,foreach效率会更高,但对于1W级的数组,还是for效率高。
http://blog.csdn.net/w2cschoo...