Three arrays were built first: $array1, $array2, $array3. The last array was a combination of $array1 and $array2. $array1 was the keys of $array3 and $array2 was the values of $array3.

  • The length of $array1 and $array1: 113 720
  • The length of $array3: 111 582

$array3 had 2 138 element less than that of $array2 or $array1. The length difference was less than 2%.

Test one: Copied a piece of text from the daily news. The text had a length of 254 bytes. Time taken for conversion:

  • str_replace( $array1, $array2, $text): 31 seconds
  • strtr($text, $array3): 5 seconds

Test two: Increased the length of the string to convert to 2008 bytes. Time taken for conversion:

  • str_replace( $array1, $array2, $text): 101 seconds
  • strtr($text, $array3): 7 seconds

Obvious, strtr has significant advantage over str_replace.

// to use str_replace()
$stime = time();
$test_text = test_string();
for ($i = 0; $i < 100; $i++) {
    str_replace($array1, $array2, $test_text);
}
echo '<li>1. ' . (time() - $stime) . " seconds</li>";
echo '<p>F ' . count($array1) . ' J ' . count($array2);

// to use strtr()
$stime = time();
for ($i = 0; $i < 100; $i++) {
    strtr($test_text, $array3);
}
echo '<li>2. ' . (time() - $stime) . " seconds</li>";
echo '<p>F2J ' . count($array3);

 

Test the speed of PHP functions: strtr and str_replace

Leave a Reply

Your email address will not be published. Required fields are marked *