strtr vs str_replace. A battle for speed and dignity.
Posted on 12.07.2009 10:15 pm
I've been doing some benchmarks on strtr() vs str_replace(). What am I looking for? Which one is faster as a template parser.
What I do is put %TAGS% in the templates like that and use a string replace tool of some sorts to replace %TAGS% with whatever content i see fit. Basic template stuff.
I've been using strtr(). Since in the initial profile of my site with strtr() and str_replace(). I concluded that strtr() was a clear winner.
But I felt that I needed to get some better results. So I setup a 128kB file with Lorem Ipsum text and set the parsers to work.
And what happened?
Short answer: str_replace() > strtr()
This is the function I am using now to parse templates.
/**
* Used to replace items in a string
* Takes an array and extracts the key and values as to what to replace
*
* Example:
* echo string_replace("Hello World", array("Hello" => "Goodbye"));
* // Goodbye World
*/
function string_replace($string, $array)
{
return str_replace(array_keys($array), array_values($array), $string);
}
Long answer:
The start of the test looked very promising for strtr(). What I did to start of was to replace a with e in the file.
// It took 1.29% out of a 8.3ms execution time
strtr($string, "a", "e");
// 7.19% out of 8.8ms
str_replace("a", "e", $string);
Next was a larger replace. a with e, i with f, r with m
// 1.25% out of 8.6ms
strtr($string, "air", "efm");
// 17.37% out of 10.7ms
str_replace(array("a", "i", "r"), array("e", "f", "m"), $string);
So replacing single letters with other single letters is clearly best suited for strtr(). Since that's it's purpose.
Next I tried was to do the same replacement but with each letter as a key / value pair in an array. This only applied to strtr since I was doing that already with str_replace.
// 37.30% out of 13.4ms
strtr($string, array("a" => "e", "i" => "f", "r" => "m"));
Ok so using arrays with strtr() takes a lot longer to execute. I did this a few times just to be sure I had the correct results.
But what I am going to be doing isn't a replace of 1 character with another. But a word replacement. So I selected two words that appear a few times in the text (4-5 time each).
// 47.10% out of 15.02ms
strtr($string, array("Class" => "Olafur", "sociis" => "Iceland"));
// 6.01% out of 8.2ms
str_replace(array("Class", "sociis"), array("Olafur", "Iceland"), $string);
That sold me. strtr() is just to slow when dealing with arrays of words.
Just as a note. I tried preg_replace and it got similar results as str_replace. A little bit slower though (3-5% in some cases)
0 9 Like it or hate it? - Comment (0)
Process time: 0.009851 seconds