Assume I have the following settings array:
$settings = array('a' => 1, 'b' => 2, 'c' => 3);
Which of the following set of codes is more efficient, in terms of speed & memory usage ?
Set 1
foreach($settings as $k => $v) {
define($k, $v);
}
Set 2
while (list($key, $value) = each($settings)) {
define($key, $value);
}
They have the same results.
UPDATE: Added benchmark results
Here are the benchmark codes:
<?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;
?>
After quite a few benchmark runs, I found that foreach()
is around 2x to 3x faster than while-list-each
approach.
Hope the above benchmark is useful to future audience.