PHP variable performance
I ran a simple test which print out the variable $var = “” (empty string) with a loop of 100,000 times for 10 times, and the average in seconds. The table below is what I get using Core 2 Duo E6320 processor.
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Avg | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| “$var” | 0.037 | 0.067 | 0.099 | 0.138 | 0.170 | 0.201 | 0.234 | 0.272 | 0.302 | 0.334 | 0.0334 |
| $var | 0.015 | 0.029 | 0.044 | 0.062 | 0.078 | 0.093 | 0.107 | 0.125 | 0.140 | 0.154 | 0.0154 |
| “{$var}” | 0.030 | 0.060 | 0.090 | 0.123 | 0.153 | 0.182 | 0.213 | 0.244 | 0.274 | 0.304 | 0.0304 |
The first case is echo “$var”, the 2nd is the traditional echo $var, and the 3rd is echo “{$var}”
It seems that by using echo $var, the speed would be a lot faster than the other 2. The first case and the 3rd case is nearly the same, with 3rd case is having slightly better performance than the first case.
For convenience, we would write echo “Today is $today” or echo “Today is {$today}“, however this would defeat the need of application to be processed in shortest time. Using echo “Today is “ . $today is a bit troublesome, but it save time and load for the server side. Furthermore, text editor often recognize and colorize the php variable outside the double quote. If the variable is placed inside the double quote, the colour would be just the same as the normal text and we would have difficulty to differenciate it in a glance.
Conclusion? It is best to use
echo “Today is ” . $variable; // best performance
Rather than
echo “Today is {$variable}”; //much slower
which is slightly better than
echo “Today is $variable”; // the slowest!
Like