• Code Optimization 2

    1) Don’t copy variables for no reason

    Sometimes PHP developer attempt to make their code “cleaner” by copying predefined variables to variables with shorter names before working with them. What this actually results in is doubled memory consumption (when the variable is altered), and therefore, slow scripts. In the following example, if a user had inserted 512KB worth of characters into a textarea field. This implementation would result in nearly 1MB of memory being used.

    1
    2
    
    $description = strip_tags($_POST['description']);
    echo $description;

    There’s no reason to copy the variable above. You can simply do this operation inline and avoid the extra memory consumption:

    1
    
    echo strip_tags($_POST['description']);

    2) Avoid doing SQL queries within a loop

    A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once.

    1
    2
    3
    4
    5
    6
    
    foreach ($userList as $user) {
      $query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] .
     
    '", "' . $user['last_name'] . '")';
      mysql_query($query);
      }

    Instead of using a loop, you can combine the data into a single database query.

    1
    2
    3
    4
    5
    6
    7
    8
    
    $userData = array();
    foreach ($userList as $user) {
        $userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")';
     }
    $query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);
    mysql_query($query);
     
    //INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...
    Tags:

Comments on this post

Leave a Reply

  • Security Code :


    6 + = nine