- microtime: documentation ( source)
- ini_set: documentation ( source)
- implode: documentation ( source)
- sprintf: documentation ( source)
<?php
// needed to cope with a million entry array
ini_set('memory_limit', '512M');
$limit = 100000;
$text[] = "Now is the time";
$text[] = "for all good men";
$text[] = "to come to the aid";
$text[] = "of their country.";
$text2['part1'] = "Now is the time";
$text2['part2'] = "for all good men";
$text2['part3'] = "to come to the aid";
$text2['part4'] = "of their country.";
$bigArray = fillArray($limit);
$max=count($bigArray);
#######################################################
$start = microtime(TRUE);
for($i=0; $i<$max; $i++) {
$bigArray[$i] = $text[0];
$bigArray[$i] .= ' ';
$bigArray[$i] .= $text[1];
$bigArray[$i] .= ' ';
$bigArray[$i] .= $text[2];
$bigArray[$i] .= ' ';
$bigArray[$i] .= $text[3];
}
$results['dotequal']['time'] = microtime(TRUE) - $start;
$results['dotequal']['name'] = 'Dot Equals';
#######################################################
$start = microtime(TRUE);
for($i=0; $i<$max; $i++) {
$bigArray[$i] = $text[0].' '.$text[1].' '.$text[2].' '.$text[3];
}
$results['concat']['time'] = microtime(TRUE) - $start;
$results['concat']['name'] = 'Dot Concatenation';
#######################################################
$start = microtime(TRUE);
for($i=0; $i<$max; $i++) {
$bigArray[$i] = "$text[0] $text[1] $text[2] $text[3]";
}
$results['replace']['time'] = microtime(TRUE) - $start;
$results['replace']['name'] = 'In-string Replacement';
#######################################################
$start = microtime(TRUE);
for($i=0; $i<$max; $i++) {
$bigArray[$i] = "{$text2['part1']} {$text2['part2']} {$text2['part3']} {$text2['part4']}";
}
$results['replace2']['time'] = microtime(TRUE) - $start;
$results['replace2']['name'] = 'Complex In-string Replacement';
#######################################################
$start = microtime(TRUE);
for($i=0; $i<$max; $i++) {
$bigArray[$i] = sprintf('%s %s %s %s', $text[0], $text[1], $text[2], $text[3]);
}
$results['sprintf']['time'] = microtime(TRUE) - $start;
$results['sprintf']['name'] = 'Function: sprintf()';
#######################################################
$start = microtime(TRUE);
for($i=0; $i<$max; $i++) {
$bigArray[$i] = implode(' ', $text);
}
$results['implode']['time'] = microtime(TRUE) - $start;
$results['implode']['name'] = 'Function: implode()';
#######################################################
foreach($results AS $test) {
echo $test['name']." -- ".sprintf("%01.6f", $test['time'])."\n";
}
#######################################################
function fillArray($limit) {
// build huge array
for($i=0; $i<$limit; $i++) {
$array[] = $i;
}
return $array;
}
?>