4

带有strpos检查的str_replace函数可以避免额外的工作吗?

方法一

...
if (strpos($text, $tofind) !== FALSE)
 $text = str_replace($tofind, $newreplace, $text);
...

方法二

...
$text = str_replace($tofind, $newreplace, $text);
...

问题:这两种方法有效,但是......我想知道 strpos-checking(或其他)是好方法还是坏方法、无用(和优化反模式)。

4

5 回答 5

4

可能会保存一些str_replace()调用,但您总是会得到额外的调用strpos()!== false比较。但是,我认为它不会产生任何可衡量的影响,只要此代码不会运行大约 100000 次(或类似)。因此,只要您不需要知道,如果要进行替换,您应该避免这种“优化”以使事情更简单和可读。

于 2011-10-14T22:44:04.980 回答
4

你总是可以自己计时:

$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

*/

strpos每次添加都会变慢,但不会慢很多。

一个好的经验法则是不要猜测你的瓶颈在哪里。功能代码和良好、简洁的设计。之后,您可以分析性能测试何时需要。

于 2011-10-14T22:49:53.970 回答
3

没有strpos的方法更好。

让我们假设 strpos 和 str_replace 都具有相同的最坏情况运行时间,因为它们都必须遍历整个文本。

通过同时使用两者,在最坏的情况下,运行时间比单独使用 str_replace 增加一倍。

于 2011-10-14T22:43:49.770 回答
0

这里的另一个基准测试结果:使用 strpos:http: //3v4l.org/pb4hY#v533没有 strpos:http: //3v4l.org/v35gT

于 2014-04-28T12:17:45.207 回答
0

我刚刚测试了 3 种方法来替换我的配置文件中的常量:

// No check
function replaceConstantsNoCheck($value)
{
    foreach (array_keys(get_defined_constants()) as $constant)
        $value = str_replace($constant, constant($constant), $value);

    return $value;
}

// Check with strstr
function replaceConstantsStrstr($value)
{
    foreach (array_keys(get_defined_constants()) as $constant)
        if (strstr($value, $constant))
            $value = str_replace($constant, constant($constant), $value);

    return $value;
}

// Check with strpos
function replaceConstantsStrpos($value)
{
    foreach (array_keys(get_defined_constants()) as $constant)
        if (strpos($value, $constant) !== false)
            $value = str_replace($constant, constant($constant), $value);

    return $value;
}

一些测量:

/*
No check : 0.0078179836273193
Strstr   : 0.0034809112548828
Strpos   : 0.0034389495849609

No check : 0.0067379474639893
Strstr   : 0.0034348964691162
Strpos   : 0.0034480094909668

No check : 0.0064759254455566
Strstr   : 0.0031521320343018
Strpos   : 0.0032868385314941

No check : 0.0068850517272949
Strstr   : 0.003389835357666
Strpos   : 0.0031671524047852

No check : 0.006864070892334
Strstr   : 0.0032939910888672
Strpos   : 0.0032010078430176
*/

在我所有的测试中,没有一种检查方法至少使用了两倍的时间!

strstrstrpos方法之间似乎没有显着差异。

于 2012-04-16T13:33:40.303 回答