PHP, Avoid overusing function calls
Date: 2007-05-26 20:55:15
Calling a function in PHP is very expensive.
Consider the following code:
<?php
function some_func() {
$j = 1;
}
$START = time();
for ($i = 0; $i < 9000000; ++$i) {
some_func();
}
$END = time() - $START;
echo "Calling the function took $END seconds\n";
$START = time();
for ($i = 0; $i < 9000000; ++$i) {
$j = 1;
}
$END = time() - $START;
echo "Inlining took $END seconds\n";
?>
In my computer, the first loop took 7 seconds and the second loop just 1 seconds. Having longer functions decreases the impact of function calls, but adding parameters and return values will increase it. For example, editing the above script so that some_func() takes just two parameters (although the function did not use them) increased the function loop execution time to 15 seconds.A huge difference, but like i read in the source:
“this one is definitely one best left until the very end - if you really need that extra bit of performance. Functions are there to centralise code and are incredibly helpful, and inlining them before you really need to definitely counts as premature optimisation…
… Expensive, yes, and expensive still, but there's a reason using functions is so addictive!”
0 comments.
