rendered paste body<?php
// preg-bench.php
// Benchmarks preg_replace using consecutive calls vs. single array
// 18.12.2005 by b1n0ry on ##php @ irc.freenode.net
$sampletext = 'text'; // text to test with should contain the word 'text'
$iterations = 100000; // number of times to execute each method
$teststoaverage = $iterations; // times to repeat the test for an average
print "Testing, be patient...";
//- Consecutive Test
$totaltesttime = 0;
for($j=0;$j < $teststoaverage;$j++) {
$text = $sampletext;
$starttime = microtime();
for($i=0;$i < $iterations;$i++) {
$text = preg_replace('/text/s','text',$text);
}
$totaltesttime = $totaltesttime + abs(microtime() - $starttime);
}
$consecutiveaverage = $totaltesttime / $teststoaverage;
//- Array Test
$totaltesttime = 0;
for($j=0;$j < $teststoaverage;$j++) {
$text = $sampletext;
$regex = array();
$replace = array();
for($i=0;$i < $iterations;$i++) {
$regex[$i] = '/text/s';
$replace[$i] = 'text';
}
$starttime = microtime();
$text = preg_replace($regex,$replace,$text);
$totaltesttime = $totaltesttime + abs(microtime() - $starttime);
unset($regex,$replace);
}
$arrayaverage = $totaltesttime / $teststoaverage;
//- Output Results
print "Done\n";
print "Average time to process $iterations consecutive preg_replace() calls (s): $consecutiveaverage\n";
print "Average time to process preg_replace() with arrays of size $iterations (s): $arrayaverage\n";
if($consecutiveaverage > $arrayaverage) {
print "Arrays win!\n";
} else {
print "Consecutive calls win!\n";
}
?>