Project

General

Profile

Bug #20068 » benchmark_trimExplode.php

Administrator Admin, 2009-02-21 14:51

 
<?php
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}


// define functions


function trimExplode($delim, $string, $onlyNonEmptyValues = false, $limit = 0) {
$array = (!$limit ? explode($delim, $string) : explode($delim, $string, $limit));
// for two perfomance reasons the loop is duplicated
// a) avoid check for $onlyNonEmptyValues in foreach loop
// b) avoid unnecessary code when $onlyNonEmptyValues is not set
if ($onlyNonEmptyValues) {
$new_array = array();
foreach($array as $value) {
$value = trim($value);
if ($value != '') {
$new_array[] = $value;
}
}
// direct return for perfomance reasons
return $new_array;
}

foreach($array as &$value) {
$value = trim($value);
}

return $array;
}


function trimExplode2($delim, $string, $removeEmptyValues = false, $limit = 0) {
$explodedValues = $limit ? explode($delim, $string, $limit) : explode($delim, $string);

$result = array_map('trim', $explodedValues);

if ($removeEmptyValues) {
$notEmpty = create_function('$string', 'return ($string != \'\');');
$result = array_values(array_filter($result, $notEmpty));
}

return $result;
}


// benchmark
$numberofRuns = 10000;
$testString = 'a, , b, , c';

$t1 = microtime_float();

for ($i = 0; $i < $numberofRuns; $i++) {
trimExplode(',', $testString, false);
}

$t2 = microtime_float();

for ($i = 0; $i < $numberofRuns; $i++) {
trimExplode2(',', $testString, false);
}

$t3 = microtime_float();


// compare


$resultOld = trimExplode(',', $testString);
$resultNew = trimExplode2(',', $testString);
$difference = array_diff($resultOld, $resultNew);


// result


echo 'runs: ' . $numberofRuns . "\n";
echo 'equal: ' . (empty($difference) ? 'yes' : 'no');
echo "\n\n";
echo "old: ".($t2-$t1);
echo "
new: ".($t3-$t2);
echo "

difference: ".((($t2-$t1)/($t3-$t2))*100).'%' . "\n";

?>
(2-2/3)