Wednesday, August 19, 2009

 

Performance of converting an integer to a string in PHP

We had a discussion at work about the fastest way to convert an integer to a string in PHP. The options were: To test the theories I ran each of those conversions a million times on PHP 5.2.8 CGI without any sort of accelerator. Casting was the fastest. Concatenation and interpolation were about same. Calling strval() took twice as long as casting. The results were:
  1. stringCasting: 0.744 s (e.g. (string)$i)
  2. stringConcatenation: 0.971 s (e.g. $i . '')
  3. stringInterpolation: 1.005 s (e.g. "$i")
  4. strvalConversion: 1.443 s (e.g. strval($i))
Here's the code I ran to get that output:
  1. <?
  2.  
  3. function timeTrial($functionName, $i) {
  4.     $start = microtime(true);
  5.     $functionName($i);
  6.     $totalTime = sprintf("%0.3f", microtime(true) - $start);
  7.     echo "<h3>$functionName: $totalTime s</h3>";
  8.     flush();
  9. }
  10.  
  11. function stringConcatenation($i) {
  12.     for ($j = 0; $j < $i; ++$j) {
  13.         if ($j . '' === $i . '') {
  14.             echo "This should never happen";
  15.         }
  16.     }
  17. }
  18.  
  19. function strvalConversion($i) {
  20.     for ($j = 0; $j < $i; ++$j) {
  21.         if (strval($j) === strval($i)) {
  22.             echo "This should never happen";
  23.         }
  24.     }
  25. }
  26.  
  27. function stringInterpolation($i) {
  28.     for ($j = 0; $j < $i; ++$j) {
  29.         if ("$j" === "$i") {
  30.             echo "This should never happen";
  31.         }
  32.     }
  33. }
  34.  
  35. function stringCasting($i) {
  36.     for ($j = 0; $j < $i; ++$j) {
  37.         if ((string)$j === (string)$i) {
  38.             echo "This should never happen";
  39.         }
  40.     }
  41. }
  42.  
  43. for ($k = 0; $k < 4; ++$k) {
  44.     $iterations = 1000000;
  45.     foreach (array("stringConcatenation", "strvalConversion", "stringInterpolation", "stringCasting") as $test) {
  46.         timeTrial($test, $iterations);
  47.     }
  48. }
  49.  

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?