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.
- Check if a string is empty
if (empty($var)) - 3 ms
X if ($var == "") - 44ms
- Compare two strings
$a == $b - 6 ms
- Check for substring (if a string contains another string)
strpos($haystack, $needle) !== false - 4 ms
X ereg($needle, $haystack) - 31 ms
- Check if a string starts with another string
strpos($haystack, $needle) === 0 - 4 ms
strpos($haystack, $needle) - 4 ms
- Check if a string ends with another string
substr($haystack, -strlen($needle)) === $needle - 6 ms
- Replace a string inside another string
str_replace($search, $replace, $subject) - 8 ms
X ereg_replace($search, $replace, $subject) - 41 ms
- Trim characters from the beginning and end of a string
trim($string, ",") - 1 ms
X preg_replace('/^,*|,*$/m', "", $string) - 47 ms
- Split a string into an array
explode(",", $string) - 10 ms
- 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
- 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. :)