Programming for efficiency

Thor

Honorary Master
Joined
Jun 5, 2014
Messages
44,236
Inspired by @[)roi(]'s Functional Programming thread I thought it might be a good idea to have a thread about programming with performance in mind, after all, if you can speed up your code by 10%, that decreases your hardware load by 10%, saving you the need to upgrade.

If you are a tad bit lazy, you might be tempted to write pages with sections of code like this:

PHP:
$result = mysqli_query($db, "SELECT * FROM Users;");
while ($row = mysqli_fetch_assoc($result)) {
    if ($row['ID'] < '30') {
        // do stuff here
    }
}

This is basically using PHP to look through the entire result set for particular rows, something SQL is better equipped to do, MySQL is lightning fast at processing queries, and modifying the above code to the following would result in a MASSIVE performance boost:

PHP:
$result = mysqli_query($db, "SELECT * FROM Users WHERE ID < 30;");
while ($row = mysqli_fetch_assoc($result)) {
    // do stuff here }

Also do not use functions that are more complex than is required for the task ie, preg_replace() is a powerful way to search and replace text in a string, but if you are not going to be using regular expressions then you should rather be using str_replace() as it's much faster.

What do I hope to achieve with this thread?

If you managed to optimize a function or the likes, please document it here. Others will find it useful and hopefully learn from you.
 
Top