Is Using Types in PHP Faster?
PHP 7 introduced the ability to add return types to functions and static types to parameters. The obvious main benefit is that it enables better hinting for using functions and cleaner code. But I wondered if there was another benefit.
Does using types make the code run faster or slower?
Hypothesis
My hypothesis is that it should be faster as knowing a type, in theory, allows PHP to compile the code that is optimised for that particular type.
Method
To find out the answer, I did a little experiment. I created this basic function:
function multiplier($n)
{
return $n * $n;
}
I also created 3 other variations of this function: one where the parameter was had a type specified, one where the return type was specified and one where both the parameter type and return type were specified.
The experiment was simple, hit each function 1,000,001 times passing the number into the function:
$start = microtime(1);
foreach (range(0, 1000000) as $n) {
multiplier($n);
}
$end = microtime(1);
I did this with each of the variations and recorded the times. I then re-ran the experiment 100 times and took an average at the end.
Results
Here are the averages:
+-------------+-------------+-------------+-------------+
| No Types | Return Type | Param Type | Both Types |
+-------------+-------------+-------------+-------------+
| 0.038639591 | 0.043333142 | 0.044089079 | 0.048477461 |
+-------------+-------------+-------------+-------------+
So we have the average when no types are used, when only the return type is used, when only the parameter type is used and when both return type and the parameter type are used.
As you can see, using types actually slows down execution rather than increase it. If you use both a return type and a parameter type, it can be up to 25% slower!
Conclusion
So to answer the original question:
Does using types make the code run faster or slower?
Based on this experiment, the answer is slower.
This is by no means a complete experiment and I am no way using this as a way of discouraging the use of types. The times are so miniscule any real difference is unnoticeable.
Just to put things into perspective, I ran the same experiment for using no types on both PHP 5.5 and PHP 5.3 just for fun. As you expect, the results are on another level:
So using types in PHP 7.0 is way fast than not using types in PHP 5. Just in case you needed another reason to upgrade to 7.
P.S.
I just wanted to take this opportunity to wish everybody a very Merry Christmas and a Happy New Year. I hope you all have a great 2017! Thank you for reading this blog!