-2

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.

Raptor
  • 53,206
  • 45
  • 230
  • 366
  • possible duplicate at http://stackoverflow.com/questions/12847502/for-loop-vs-while-loop-vs-foreach-loop-php – trallallalloo Sep 30 '15 at 08:51
  • might be a duplicate, but mixing with `list()` and `each()` make the comparison case more complicated. – Raptor Sep 30 '15 at 08:53
  • 1
    Why don't you benchmark it for your self –  Sep 30 '15 at 08:55
  • @Dagon added back benchmark results after half year... – Raptor Mar 18 '16 at 10:08
  • Your benchmark is pretty self-explanatory. The question is: do you have 100K items in the settings list in your application? And, if you create constants out of them using this approach, do you really use all of them in the rest of the code? – axiac Mar 18 '16 at 10:30
  • Agreed with you. 100,000 records are for benchmark only. Normally I will use around 10 only. – Raptor Mar 18 '16 at 10:31

1 Answers1

1

On one hand, foreach need to worry about traversable, so in this case may be little overhead compering with each in while.

But on other hand, using each and while you are using two two language constructs and one function.

Also you do need to remember that after each will finished, the cursor will be in the last element of array, if it iterate threw all elements.

sergio
  • 5,210
  • 7
  • 24
  • 46