htmlspecialchars($string, ENT_NOQUOTES);
... is about 2.5 times slower than:
str_replace(array('&', '<', '>'), array('&', '<', '>'), $string);
Does htmlspecialchars
do something that the str_replace
line doesn't?
p.s. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With