|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-01-03 14:34 UTC] 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! PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Oct 28 01:00:01 2025 UTC |
With the release of 5.4.12 strtr() now triggers a Notice (Notice: Array to string conversion in ...) if one of the array elements is an array (using the two arguments variant), even if the key is not used/found in the string (first argument) so this: <?php echo strtr('aa, bb', array( 'aa'=>'qqq', 'bb'=>'www', 'cc'=>array('what', 'ever') ) ); Before 5.4.12 strtr() triggered the notice only if the key was found in the string I don't know if this is as intended, but breaks existing application behavior (Kohana 3.3) Regards