I'm curious what the most performant method of doing string transformations is. Given a n input string and a set of translations, what method is the most efficient in general? I currently use strtr()
, but have tested various looping methods, str_replace()
with an array, etc. The strtr()
method benchmarks the fastest on my system, depending on the translations, but I'm curious if there are faster methods I haven't thought of yet.
If it's pertinent, my particular use case involves transforming 2-byte strings into ANSI color sequences for a terminal. Example:
// In practice, the number of translations is much greater than one...
$out = strtr("|rThis should be red", array('|r' => "\033[31m"));
For simple replacements,
strtr
seems to be faster, but when you have complex replacements with many search strings, it appears thatstr_replace
has the edge.strtr() performs best with straight character replacements. Longer strings give str_replace() the edge.
For example, the code below yields the following results on my (shared web hosting) system:
When we take out 'delimiter' and 'truncate', results become:
So, as of PHP 7.0.6, strtr() suffers a considerable penalty with longer replacements. The code:
Note:
This sample code is not meant as a production alternative to mysqli::real_escape_string in lieu of a DB connection (there are issues around binary/multi-byte encoded input).
Clearly, the differences are minor. For mnemonic reasons (how matches and replacements are organized) I prefer the associative array that strtr takes natively. (Not that it can't be achieved with array_keys() for str_replace.) The differences in this case are definitely within the realm of micro-optimizations, and can be very different with different inputs. If you need to process huge strings thousands of times per second, benchmark with your specific data.
I made a trivial benchmark for personal needs on the two functions. The goal is to change a lowercase 'e' to an uppercase 'E'.
This code using
str_replace
runs in 6 seconds. Now the same with thestrtr
function :It took only 4 seconds.
So as stated by T0xicCode, for this particularly simple case,
strtr
is indeed faster thanstr_replace
, but the difference is not so significant.