26-03-1394، 07:36 ب.ظ
<?php //============================== //fastMapTree.php function fastMapTree($dataset) { $tree = array(); foreach ($dataset as $id=>&$node) { if ($node['parent_id'] === null) { $tree[$id] = &$node; } else { if (!isset($dataset[$node['parent_id']]['child'])) $dataset[$node['parent_id']]['child'] = array(); $dataset[$node['parent_id']]['child'][$id] = &$node; } } return $tree; } //======================================================= //slowMapTree.php function slowMapTree($dataset, $parent=null, $levels=0) { if ($levels > 100) { print ('Possible infinite recursion'); return; } $tree = array(); foreach ($dataset as $id=>$node) { if ($node['parent_id'] !== $parent) continue; $node['child'] = slowMapTree($dataset, $id, $levels+1); $tree[$id] = $node; } return $tree; } //======================== // Build a random dataset $maxNodes = 1000; $dataset = array(); for ($i=0;$i<$maxNodes;$i++) { $parent = rand(-1,$i-1); // We use $i rather than maxNodes here to avoid infinite loops if ($parent == -1) $parent = null; $dataset[$i] = array( 'name'=>'Node '.$i, 'parent_id'=>$parent ); } //======================== // Initialize variables $startTime = 0; $endTime = 0; $tree = array(); // Build tree $startTime = microtime(true); $tree = slowMapTree($dataset); $endTime = microtime(true); // Print benchmark print '<h2>Benchmark slowMapTree</h2>'; print ($endTime-$startTime).' seconds<br>'; //======================== // Initialize variables $startTime = 0; $endTime = 0; $tree = array(); // Build tree $startTime = microtime(true); $tree = fastMapTree($dataset); $endTime = microtime(true); // Print benchmark print '<h2>Benchmark fastMapTree</h2>'; print ($endTime-$startTime).' seconds<br>';