Man*_*anz 5 php micro-optimization strpos str-replace
带strpos检查的str_replace函数可以避免额外的工作吗?
方法一
...
if (strpos($text, $tofind) !== FALSE)
$text = str_replace($tofind, $newreplace, $text);
...
Run Code Online (Sandbox Code Playgroud)
方法2
...
$text = str_replace($tofind, $newreplace, $text);
...
Run Code Online (Sandbox Code Playgroud)
问题:这两种方法有效,但是...我想知道 strpos 检查(或其他)是好方法还是坏方法,无用的方法(以及优化反模式)。
您可能会节省一些str_replace()呼叫,但您总是会收到额外的strpos()呼叫和!== false比较。然而,我认为,只要这段代码不会运行大约 100000 次(或类似的次数),它就不会产生任何可衡量的影响。因此,只要您不需要知道,如果需要进行替换,您就应该避免这种“优化”,以使事情更加简单和可读。
您始终可以自己计时:
$start = 0; $end = 0;
$tofind = 'brown';
// A
$start = microtime(true);
for ($a=0; $a<1000; $a++) {
if (strpos('The quick brown fox', $tofind) !== FALSE)
str_replace($tofind, 'red', 'The quick brown fox');
}
$end = microtime(true);
echo $end - $start . "<br />\n";
// B
$start = microtime(true);
for ($b=0; $b<1000; $b++) {
str_replace($tofind, 'red', 'The quick brown fox');
}
$end = microtime(true);
echo $end - $start . "<br />\n";
/*
various outputs:
0.0021979808807373
0.0013730525970459
0.0020320415496826
0.00130295753479
0.002094030380249
0.0013539791107178
0.0020980834960938
0.0013020038604736
0.0020389556884766
0.0012800693511963
0.0021991729736328
0.0013909339904785
0.0021369457244873
0.0012800693511963
*/
Run Code Online (Sandbox Code Playgroud)
strpos每次添加都会变慢,但不会慢很多。
一个好的经验法则是不要猜测你的瓶颈在哪里。功能代码和良好、简洁的设计。之后,您可以在性能测试需要时进行分析。