Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

p.s. I measured speed in PHP 5.4, using microtime.

like image 701
Emanuil Rusev Avatar asked May 05 '13 12:05

Emanuil Rusev


2 Answers

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.

like image 91
Denis de Bernardy Avatar answered Oct 26 '22 14:10

Denis de Bernardy


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.

like image 34
Sverri M. Olsen Avatar answered Oct 26 '22 13:10

Sverri M. Olsen