Sunday, October 21, 2012

PHP Performance Benchmarks

So a friend gave me a link that contains performance benchmarks for PHP.  It's really interesting because you might find a thing or two which you previously believed to be the best way to implement something, when actually it's the worst.  But that's just the worst case.  Still, I think it's pretty useful to know what to avoid, and the alternatives to it.  Here's the link:
        http://maettig.com/code/php/php-performance-benchmarks.php

To summarize, I will list the best implementation in terms of speed for each of the cases from the link above.  Of course, these may be the fastest implementation but they might not exactly be the simplest implementation or the most convenient, but that depends on your needs.

  1. Check if a string is empty
              if (empty($var))     - 3 ms
      X      if ($var == "")    - 44ms

  2. Compare two strings
              $a == $b     - 6 ms

  3. Check for substring (if a string contains another string)
              strpos($haystack, $needle) !== false     - 4 ms
      X      ereg($needle, $haystack)    - 31 ms

  4. Check if a string starts with another string
              strpos($haystack, $needle) === 0    - 4 ms
              strpos($haystack, $needle)    - 4 ms

  5. Check if a string ends with another string
              substr($haystack, -strlen($needle)) === $needle     - 6 ms

  6. Replace a string inside another string
              str_replace($search, $replace, $subject)     - 8 ms
      X      ereg_replace($search, $replace, $subject)     - 41 ms

  7. Trim characters from the beginning and end of a string
              trim($string, ",")     - 1 ms
      X      preg_replace('/^,*|,*$/m', "", $string)     - 47 ms

  8. Split a string into an array
              explode(",", $string)     - 10 ms

  9. Loop a numerical indexed array of strings
              $i = count($array); while($i--)     - 1 ms
              for ($i = 0, $count = count($array); $i < $count; $i++)
                        - 1 ms
      X      for ($i = 0; $i < count($array); $i++)     - 43 ms

  10. Implode an array
              "$array[0] $array[1] $array[2]"     - 5 ms
              implode(" ", $array)     - 5ms

Though differences in execution time between some implementations may be small, I still think it's good to optimize as much as we can.  I know I might be biased on this since I prefer to optimize time over space - actually, having said this, I am indeed biased - but I believe that there is no harm in switching some lines of code, as long as it does what it's supposed to do, only a little faster. :)

No comments:

Post a Comment