note 55648 deleted from language.references.pass by derick

From: Date: Mon, 15 Aug 2005 18:11:11 +0000
Subject: note 55648 deleted from language.references.pass by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-93688@lists.php.net to get a copy of this message
Note Submitter: jw at shapers dot nl ---- Don't use pass-by-reference when you want to modify large arrays. Instead, just pass by copy and return the modified array, or use the PHP functions array_map, array_walk, the latter being just a tiny bit quicker. Test script: (you may lower N to 12 or 11 on slower PC's) <?php set_time_limit(0); // it will take some time... define("N", 13); // number of arrays // calculate time in ms function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } // 4 different simple array modifiers: function doSomethingByRef(& $a) { for($i = 0; $i < sizeof($a); $i++) $a[$i]++; } function doSomethingByCopy($a) { for($i = 0; $i < sizeof($a); $i++) $a[$i]++; return $a; } function doSomethingWalk($i) { $i++; } function doSomethingMap($i) { return ++$i; } // end modifiers // test function call N times and // take time sample after each test: function testFunctionCall($call) { // setup N arrays of 2^N length $b = array(); for($i = 0; $i < N; $i++) { $b[$i] = array(); for($j = 0; $j < pow(2, $i); $j++) $b[$i][$j] = 0; } // call function on N arrays $samples = array(); for($i = 0; $i < N; $i++) { $a = $b[$i]; array_push($samples, microtime_float()); eval($call); } array_push($samples, microtime_float()); return $samples; } // run tests on 4 array modifiers: $byRef = testFunctionCall("doSomethingByRef(\\$a);"); $byCpy = testFunctionCall("\\$a = doSomethingByCopy(\\$a);"); $byMap = testFunctionCall("\\$a = array_map(\\"doSomethingMap\\", \\$a);"); $byWlk = testFunctionCall("array_walk(\\$a,\\"doSomethingWalk\\");"); // output result: echo "<pre>"; echo "Size\\tPassed array by Ref\\tReturn modified array\\t"; echo "Use array_map\\t\\tUse array_walk\\n"; echo "--------------------------------------------------"; echo "--------------------------------------------------\\n"; for($i = 1; $i < sizeof($byCpy); $i++) { echo pow(2, $i - 1)."\\t"; echo str_pad($byRef[$i] - $byRef[$i-1], 20)."\\t"; echo str_pad($byCpy[$i] - $byCpy[$i-1], 20)."\\t"; echo str_pad($byMap[$i] - $byMap[$i-1], 20)."\\t"; echo str_pad($byWlk[$i] - $byWlk[$i-1], 20)."\\n"; } ?>

« previous php.notes (#93688) next »