简体   繁体   中英

Why is “htmlspecialchars” so slow?

htmlspecialchars($string, ENT_NOQUOTES); 

... is about 2.5 times slower than:

str_replace(array('&', '<', '>'), array('&amp;', '&lt;', '&gt;'), $string);

Does htmlspecialchars do something that the str_replace line doesn't?

ps I measured speed in PHP 5.4, using microtime .

str_replace() treats strings as ASCII C-strings. htmlspecialchars() does not. (It's UTF8 strings by default in php 5.4, if memory serves.)

Also, there's code in htmlspecialchars() to avoid double-encoding, etc. It does more stuff.

Look at the documentation .

The reason it is slower is because it does more. It handles various quotes, encodings and double encodings.

Working with encodings can be quite slow. Because computers are very fast it should not matter much, but if you compare it against a simple search and replace (which is basically all str_replace does) it will be slower.

该文档指出htmlspecialchars()有一个参数,您可以在其中输入您要使用的字符集,默认情况下它还会对所有内容进行两次编码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM