Nogle der kan bekræfte at foreach() er det hurtigeste alternativ:
Testet på Ubuntu med 1GB ram, PHP 5.3.4.
- <?php
- $range = range(0, 100000);
- $result = array();
-
- $fn = function(&$item, $k = null) use ($result) {
- if(($pos = strpos($item, ':')) !== false) {
- $result[substr($item, $pos+1)] = 1;
- }
- };
- $fn2 = function(&$item) use ($result) {
- if(($pos = strpos($item, ':')) !== false) {
- $result[substr($item, $pos+1)] = 1;
- }
- };
- $fn3 = function(Iterator $iterator) use ($result) {
- $item = $iterator->current();
- if(($pos = strpos($item, ':')) !== false) {
- $result[substr($item, $pos+1)] = 1;
- }
- return true;
- };
-
- echo 'array_map()<br />';
- $result = array();
- $start = microtime(true);
- array_map($fn2, $range);
- echo 'time: '. round(microtime(true)-$start,4).' mem: '.round(memory_get_usage(true)/1048576,2).'<br /><br />';
-
-
- echo 'array_walk()<br />';
- $result = array();
- $start = microtime(true);
- array_walk($range, $fn);
- echo 'time: '. round(microtime(true)-$start,4).' mem: '.round(memory_get_usage(true)/1048576,2).'<br /><br />';
-
-
- echo 'iterator_apply()<br />';
- $result = array();
- $start = microtime(true);
- $it = new ArrayIterator($range);
- iterator_apply($it, $fn3, array($it));
- echo 'time: '. round(microtime(true)-$start,4).' mem: '.round(memory_get_usage(true)/1048576,2).'<br /><br />';
-
-
- echo 'foreach() with function<br />';
- $result = array();
- $start = microtime(true);
- foreach($range as $item) {
- $fn2($item);
- }
- echo 'time: '. round(microtime(true)-$start,4).' mem: '.round(memory_get_usage(true)/1048576,2).'<br /><br />';
-
-
-
- echo 'foreach()<br />';
- $result = array();
- $start = microtime(true);
- foreach($range as $item) {
- if(($pos = strpos($item, ':')) !== false) {
- $result[substr($item, $pos+1)] = 1;
- }
- }
- echo 'time: '. round(microtime(true)-$start,4).' mem: '.round(memory_get_usage(true)/1048576,2).'<br /><br />';
Resultater:
array_map()
time: 0.2703 mem: 12
array_walk()
time: 0.1578 mem: 12
iterator_apply()
time: 0.2354 mem: 17.75
foreach() with function
time: 0.1329 mem: 17.75
foreach()
time: 0.093 mem: 17.75
Indlæg senest redigeret d. 20.06.2012 13:42 af Bruger #10216