Three PHP Performance Tips

PHP
28th June 2019 Three PHP Performance Tips

There are plenty of ways you can improve the performance of your PHP coding, so here I take a quick look at my main three performance tips that I always try to keep in mind when developing.

1. Take advantage of native PHP functions

PHP comes with a shed load of native functions. Wherever possible, try to take advantage of them instead of writing your own functions to achieve the same outcome. There's no reason to flex your PHP skills unnecessarily when all you're doing is recreating what already exists, just with a different name. Just taking a little bit of time to learn how to use PHP's native functions will not only help you write code faster but will also make it more efficient. And isn't that the aim?

2. Don't copy variables for no reason

I think most programmers have seen some code where you see something like $name = $longername. You now have two variables holding the exact same piece of information, which could potentially be a large piece of information. Sure, it looks "cleaner" by copying predefined or larger-named variables to variables with shorter names before working with them, but that's doubling memory consumption (when the variable is altered). If you have a variable that's 512KB worth of characters into a textarea field, like a particularly long article or array of data, then duplicating the variable would result in nearly 1MB of memory being used.

3. Avoid SQL queries within a loop

Another that I've seen before, and I'm sure others have, but a common mistake is placing a SQL query inside of a loop. If you have a loop that goes around a thousand times, then that's trips to the database and significantly slower scripts. Instead, look at using things like subselects, joins and joins with group bys. If you're inserting data into a database, store that information into an array and put them into the database in one query.