[英]Which of the followings is more efficient?
假設我有以下設置數組:
$settings = array('a' => 1, 'b' => 2, 'c' => 3);
在速度和內存使用方面,以下哪組代碼更有效?
設置 1
foreach($settings as $k => $v) {
define($k, $v);
}
2套
while (list($key, $value) = each($settings)) {
define($key, $value);
}
他們有相同的結果。
更新:添加了基准測試結果
以下是基准代碼:
<?php
header('Content-Type: text/plain');
$arr = array();
for($i = 0; $i < 100000; $i++) {
$arr['rec_' . $i] = md5(time());
}
$start = microtime(true);
foreach ($arr as $k => $v) {
define($k, $v);
}
$end = microtime(true);
echo 'Method 1 - Foreach: ' . round($end - $start, 2) . PHP_EOL;
$arr = array();
for($i = 0; $i < 100000; $i++) {
$arr['rec2_' . $i] = md5(time());
}
$start = microtime(true);
while (list($key, $value) = each($arr)) {
define($key, $value);
}
$end = microtime(true);
echo 'Method 2 - While List Each: ' . round($end - $start, 2) . PHP_EOL;
?>
經過多次基准測試后,我發現foreach()
比while-list-each
方法快 2 到 3 倍。
希望上述基准對未來的觀眾有用。
一方面, foreach
需要操心穿越,所以在這種情況下,可能只有極少的開銷compering each
在while
。
但另一方面,使用each
和while
您正在使用兩種兩種語言結構和一種函數。
Also
你需要記住,以后each
都會結束,光標會在數組的最后一個元素,如果迭代把所有的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.