php - Which of the followings is more efficient? -


assume have following settings array:

$settings = array('a' => 1, 'b' => 2, 'c' => 3); 

which of following set of codes more efficient, in terms of speed & memory usage ?

set 1

foreach($settings $k => $v) {     define($k, $v); } 

set 2

while (list($key, $value) = each($settings)) {     define($key, $value); } 

they have same results.


update: added benchmark results

here 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 $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 few benchmark runs, found foreach() around 2x 3x faster while-list-each approach.

hope above benchmark useful future audience.

on 1 hand, foreach need worry traversable, in case may little overhead compering each in while.

but on other hand, using each , while using 2 two language constructs , 1 function.

also need remember after each finished, cursor in last element of array, if iterate threw elements.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -