[php]vsprintf VS preg_replace
I want to formart a simple string in PHP. There are two ways to do this. One is vsprintf and another preg_replace. But who is faster? I have tested both of them. I find that vsprintf run more faster while can parse string in many formart. So why not use vsprintf to replcae preg_replace if it is possible?
<?php
//test start
$start_time = microtime();$f = ‘who is faster? Name: %1$s, Id: %2$s, Year: %3$s, Home: %4$s’;
$arg = array(’Lucky Mouse’, ‘000000001(Xydw.com)’, ‘20090526′, ‘China On Earth 地球 - 中国’);//preg_replace append 0 first
array_unshift($arg, ‘null’);for($i = 0; $i < 1000; $i ++) {
$a[] = preg_replace(”/%([0-9]+)\\\$s/e”, ‘$arg[$1]‘, $f);
//$a[] = vsprintf($f, $arg);
}
echo $a[0].’<br />’;//end test
$end_time = explode(” “, microtime());
$end_time = $end_time[0] + $end_time[1];
$start_time = explode(” “, $start_time);
$start_time = $start_time[0] + $start_time[1];
echo number_format($end_time - $start_time, 5);
?>
vsprintf finish in about : 0.01 s
preg_repace finish in about: 0.08s