为什么"htmlspecialchars"这么慢?

Ema*_*sev 13 php performance

htmlspecialchars($string, ENT_NOQUOTES); 
Run Code Online (Sandbox Code Playgroud)

... 比以下慢大约2.5倍:

str_replace(array('&', '<', '>'), array('&amp;', '&lt;', '&gt;'), $string);
Run Code Online (Sandbox Code Playgroud)

是否htmlspecialchars做一些事情,该str_replace行不?

ps我用PHP测量了PHP 5.4的速度microtime.

Den*_*rdy 12

str_replace()将字符串视为ASCII C字符串.htmlspecialchars()才不是.(如果内存服务的话,默认情况下它是php 5.4中的UTF8字符串.)

此外,还有代码htmlspecialchars()可以避免双重编码等.它会做更多的事情.