Hey everyone!
We all know that there are some methods in PHP that are just damn slow... But there are others we don't know are slowing us down.
When it comes down to it, any speed saved is good as it also saves CPU cycles and potentially saves memory (though not always the case). I would like everyone to post their speed tests here. We can make a list of methods and coding styles that are the fastest. =)
Just so we're all on the same page, we should use the same speed function. this is what I have:
PHP Code:
function MicrotimeFloat() { // from php.net/microtime
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function GetTimeDifference($time1,$time2) {
return number_format( ($time2 - $time1) , 2);
}
// then i will use:
$StartTime = MicrotimeFloat();
// do stuff here to time
$EndTime = MicrotimeFloat();
echo "This took this many seconds: ". GetTimeDifference($StartTime, $EndTime);
First off the bat, I'm going to do string concatenation. These are the 4 methods I'll test (On PHP Version 5.2.2):
PHP Code:
$strInputString = 'This string is inside another string';
$strMethodOne = "This is my string " . $strInputString . " another section";
$strMethodTwo = "This is my string $strInputString another section";
$strMethodThree = "This is my string {$strInputString} another section";
$strMethodFour = sprintf("This is my string %s another section", $strInputString );
I looped each one 1,000,000 times. These are the resilts I got (4 times each):
Method One: 0.34, 0.38, 0.32, 0.32 secs
Method Two: 0.41, 0.40, 0.41, 0.40 secs
Method Three: 0.39, 0.42, 0.41, 0.42 secs
Method Four: 0.99, 0.98, 0.99, 0.98 secs
Averages: (rounded to 2 places)
Method One: 0.34 secs Using:
"s".$str."s";
Method Two: 0.41 secs Using:
"s $str s";
Method Three: 0.41 secs Using:
"s {$str} s";
Method Four: 0.99 secs Using:
sprintf()
Using sprintf is by far the slowest here. I wasn't a fan of sprintf anyway, so that was kinda a weight off my shoulder. The best seems to be the old dot method, which takes about 1/3 the time that sprintf does.
Though, this will obviously not make a significant impact on your script either way (notice its a million times just for those low speeds!), it's good to know which is actually quickest.
I have to run off atm, but I'll post more speed tests later. Also if anyone else has any, post here, it'd be great to have a large collection for everyone to reference.
Oh and if you think I've done something wrong with my method here, let me know. :)