PHP Performance Tip: Use fully-qualified function calls when working with namespaces

TIL: When working with namespaced files in PHP it’s a huge performance win when using fully-qualified function calls.

~

If you’re calling is_null in your code, PHP will first check for the function’s existence in the current namespace. If not found there, it will look for the function in the global namespace. This extra check is quite a drag, as detailed in this issue for the SCSS PHP Project.

If you do want to target PHP’s built-in is_null (or any other global function), it’s more performant to refer to it using it’s fully-qualified name, e.g. \is_null

❌ Slow:
is_null();

✅ Fast:
\is_null();

Alternatively you can also import the function first through a use statement.

✅ Fast:
use function is_null;
is_null();

~

In the case of SCSS PHP the change from is_null to \is_null lead to a 28% speed increase!. If you’re looking for more benchmarks, Toon Verwerft has done some benching in the past.

Did this help you out? Like what you see?
Thank me with a coffee.

I don\'t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!

BuymeaCoffee (€3)

To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.

Via this tweet that sparked my quest into knowing more about this.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.