Edit report at https://bugs.php.net/bug.php?id=63893&edit=1
ID: 63893 Updated by: cataphr...@php.net Reported by: scope at planetavent dot de Summary: poor efficiency of strtr() using array with keys of very different length Status: Assigned Type: Bug Package: Strings related Operating System: Windows Server 2008 / RHEL 6.3 PHP Version: 5.4.10 Assigned To: cataphract Block user comment: N Private report: N New Comment: My patch so far: https://github.com/cataphract/php-src/compare/strtr Previous Comments: ------------------------------------------------------------------------ [2013-01-03 14:34:36] scope at planetavent dot de Description: ------------ As the documentation of strtr() points out, strtr "... will be the most efficient when all the keys have the same size". Using keys of very different lengths results in poor performance, even on very small inputs. If the str_repeat() for "m" in the test script is adjusted to 20000 the resulting runtime increases to 45 seconds for strtr() while str_replace() does not increase notably. There are cases where the replacement array is built dynamically, so there might be little control over the keylengths. It's easy to expand the example such that strtr() takes several hours compared to just a few seconds using str_replace(). Test script: --------------- <?php $text = str_repeat( 'm', 2000 ); $long_from_a = str_repeat( 'a', 1 ); $long_from_x = str_repeat( 'x', 1500 ); $replacements = array( $long_from_a => 'b', $long_from_x => 'y' ); $start = microtime( true ); $result_1 = strtr( $text, $replacements ); echo "strtr: " . number_format( microtime( true ) - $start, 4 ) . "\n"; $start = microtime( true ); $result_2 = str_replace( array_keys( $replacements ), array_values( $replacements ), $text ); echo "str_replace: " . number_format( microtime( true ) - $start, 4 ) . "\n"; echo $result_1 === $result_2 ? "results match!\n": "no match!\n"; Expected result: ---------------- strtr: 0.0001 str_replace: 0.0001 results match! Actual result: -------------- strtr: 2.4203 str_replace: 0.0001 results match! ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=63893&edit=1