I was writing some simple file manipulation and a thought came up if it wouldn’t be faster if I saved the string size in variable. It showed up that it is 10 times faster.
Using this code:
include "../classes/Timer.class.php";
$t = new Timer(); //Timer class I've written for this purpose [link below]
$multiplyer = 3000000; //Times to try the operation
$string = str_repeat("ggggggggggg",2); //I first tried 2000 here, but for 2 there are same results
$t("calling"); //Saving time
for($i=0; $i<$multiplyer; $i++) {
$size = strlen($string);
$size2 = strlen($string);
$size3 = strlen($string);
}
$t("clover");
$t("caching"); //Saving time
for($i=0; $i<$multiplyer; $i++) {
$size = strlen($string);
$size2 = $size;
$size3 = $size;
}
$t("chover");
$total = $t["calling-clover"]+$t["caching-chover"]; //percents are usefull :)
echo "Calling: {$t["calling-clover"]} (".round(($t["calling-clover"]/$total)*100)."%)<br>\n";
echo "Caching in variables: {$t["caching-chover"]} (".round(($t["caching-chover"]/$total)*100)."%)<br>\n";
Results:
Calling: 1.988455057 (67%)
Caching in variables: 0.984993458 (33%)
What is even more interesting is the fact, that it does not matter what number I put in the str_repeat call, so the strlen obviously does not compute anything – the size must be saved somewhere and strlen is just function that returns value.
This implies:
Are really function calls so slow?
If not, is this strlen specific?
There is much more to a function call than a variable retrieval. Every time you execute a function: