Thursday, June 26, 2008

preg_replace_callback VS preg_replace

Some interesting results of a test between the preg_replace_callback function VS the preg_replace function using the e pattern modifier.

Here's the test code.
function uppers($match)
return strtoupper($match[0]);
$out = '12345678901234567890123456789012';
$strs = array();
$str_count = 1000;
$strs[] = md5($str_count . microtime());

foreach($strs as &$str)
$out = preg_replace('#[ace]+#e', 'strtoupper($0)', $str);

foreach($strs as &$str)
$out = preg_replace_callback('#[ace]+#', 'uppers', $str);


The test was benchmarked using the profiler included in the Xdebug Debugger and Profiler Tool for PHP.
OS is Ubuntu 8.04, Apache version 2.2.8, PHP version 5.2.4
Profiler output is being viewed in KCachegrind.

Here's the callee map generated from the output.

And here's the slightly easier to understand source map.

The two numbers on the left are the percentage of the total runtime dedicated to the actions next to them.
It appears to me that the preg_replace_callback way is faster, but I would love to see how it performs on other OS's if anyone cares to do their own tests & comment.

No comments: