Why should we care about code performance?
Small decisions made toward code performance when totaled over the span of our careers can make a significant impact in our world. The impact is not making a program “run fast”. The impact is saving invaluable human time and bringing everyone closer to carbon-neutral.
As developers, it’s essential to consider how we put the electrons flowing through our apps to use. Each decision we make can add up (even if we’re not using a programming language built for raw speed).
When we make informed decisions in our daily work we unlock the potential to make the world a better place to live. Yes, even in the small choices we make when writing PHP code. How ridiculous is that!
A first step to making that kind of impact is found in adopting new habits into our daily work. For example, we create and call functions every day in every application we make. In PHP how can we make better choices toward performance with functions?
The results might shock you.
Caller Type | 100 Calls | 10,000 Calls | 1,000,000 Calls |
Standard function | 0.176ms | 8.596ms | 612.005ms |
Static class method | 0.200ms | 9.607ms | 731.104ms |
Object method (Same Instance) | 0.211ms | 9.848ms | 787.301ms |
Anonymous function | 0.274ms | 14.389ms | 1109.482ms |
Object method (new instance per call) | 0.333ms | 16.658ms | 1295.540ms |
Static class method called through __callStatic | 0.427ms | 30.995ms | 2495.849ms |
Object method called through __call (same instance) | 0.427ms | 31.863ms | 2422.210ms |
Object method called through __call (new instance per call) | 0.541ms | 38.024ms | 3020.802ms |
The results here reveal that a standard function call in PHP is the most performant type of caller (1.5 times after then an anonymous function call).
// Standard Function: Fastest Caller
function my_function($a, $b) {
return $a <=> $b;
}
echo my_function(1,2);
With this list considered, I’ve found I need to use anonymous functions a lot less (particularly when those functions are used a lot).
// Anonymous Function: Slower Caller
echo ( fn($a, $b) => $a <=> $b )(1,2);
All things considered, performance is only one variable within the body of work. Other considerations also exist. Space used, code maintainability, and a program’s lifetime value are some of those considerations. A project needs its own consideration each time we put out hands to the keys.
Regardless, making good habits toward performance is a noble goal.
P.S. Namespaces had no impact on these results when I used them. I used namespaces on functions and class definitions.
Leave a Reply