Use your tools wisely

At various times through my PHP career, I have seen pages with sections of code like this:

$result = mysql_query("SELECT * FROM Users;");
while (
$row = mysql_fetch_assoc($result)) {
    if (
$row['ID'] == '3') {
        
// do stuff here
    
}
}

As you can see, they are using PHP to filter their SQL results - looking through the entire result set for a particular row.

SQL is designed to extract specific data from a database, and you should exploit its power as much as possible. MySQL is blazingly fast at processing queries, and modifying the above code to the following would yield an exponential speed increase:

$result = mysql_query("SELECT * FROM Users WHERE ID = 3;");
while (
$row = mysql_fetch_assoc($result)) {
    
// do stuff here
}

For very complicated SQL manipulation, you should use temporary tables - more information can be found on temporary tables in the Databases chapter.

A similar problem exists when people use functions that are more complex than is required for the task. For example, preg_replace() is a powerful way to search and replace text in a string, but if you are not doing regular expressions you should be using str_replace() as it's much faster. Similarly, explode() is a better choice than preg_split() when regular expressions are not required.

 

Next chapter: Avoid functions for maximum performance >>

Previous chapter: Write your code sensibly

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar