簡體   English   中英

以下哪個更有效?

[英]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 eachwhile

但另一方面,使用eachwhile您正在使用兩種兩種語言結構和一種函數。

Also你需要記住,以后each都會結束,光標會在數組的最后一個元素,如果迭代把所有的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM