Performance Tips to speed up PHP

Performance Tips to speed up PHP

Most of the programmers just writing code to execute the application But they bit lazy to write performance code which will make application to run faster.

Writing and executing code anyone can do, But what do you think if your code will executing perfectly with better performance ?? 

Here is some sort of performance tips which will make your code to execute faster with better performance :

  • Avoid needlessly copying variables. If the variable is quite large, this could result in a lot of extra processing. Use the copy you already whenever possible, even if it doesn’t look pretty (e.g., $_POST['somevariable']).
  • Debug with error_reporting(E_ALL). Every warning is a performance improvement waiting to happen, but only if you can see it. Cleaning up warnings and errors beforehand can also keep you from using @ error suppression, which is expensive. Just don’t forget to turn off error reporting when you’re done; warnings and errors are expensive as well.
  • Pass unchanged variables to a function by reference rather than value. This goes hand-in-hand with the point about needlessly copying variables. Much of the time, your functions only need to use the values from their parameters without changing them. In such cases, you can safely pass those parameters by reference (e.g., function(&$parameter) rather than function($parameter)) and avoid having to make memory-intensive copies.
  • Use echo instead of print(). As a language construct rather than a function, echo has a slight performance advantage over print().
  • Avoid function tests in loop conditionals. If you’re looping through an array, for example, count() it beforehand, store the value in a variable, and use that for your test. This way, you avoid needlessly firing the test function with every loop iteration.
  • Use include() and require() instead of include_once() and require_once(). There’s a lot of work involved in checking to see if a file has already been included. Sometimes it’s necessary, but you should default to include() and require() in most situations.
  • Use full file paths on include/require statements. Normalizing a relative file path can be expensive; giving PHP the absolute path (or even “./file.inc”) avoids the extra step.
  • Favor built-in functions over custom functions. Since PHP has to take the extra step of interpreting your custom functions, built-in functions have a performance advantage. More importantly, there are a lot of useful built-in functions that you may never learn about if you always default to writing your own.
  • Echo with commas, not periods. I’m a repeat offender of this one. If you use periods, PHP has to concatenate the string before it outputs. If you use commas, it just outputs them in order with no extra processing.

Caching: the Ultimate Speed Booster

 

One of the secrets of high performance is not to write faster PHP code, but to avoid executing PHP code by caching generated HTML in a file or in shared memory. The PHP script is only run once and the HTML is captured, and future invocations of the script will load the cached HTML. If the data needs to be updated regularly, an expiry value is set for the cached HTML. HTML caching is not part of the PHP language nor Zend Engine, but implemented using PHP code. There are many class libraries that do this. One of them is the PEAR Cache, which we will cover in the next section. Another is the Smartytemplate library.

Finally, the HTML sent to a web client can be compressed. This is enabled by placing the following code at the beginning of your PHP script:

<?php

ob_start("ob_gzhandler");

:

?>

If your HTML is highly compressible, it is possible to reduce the size of your HTML file by 50-80%, reducing network bandwidth requirements and latencies. The downside is that you need to have some CPU power to spare for compression

 

 

High Return Code Optimizations

The places where such high returns are achievable are in the while and for loops that litter our code, where each slowdown in the code is magnified by the number of times we iterate over them. The best way of understanding what can be optimized is to use a few examples:

Example 1

Here is one simple example that prints an array:

for ($j=0; $j<sizeof($arr); $j++) 
    echo $arr[$j]."<br>";

This can be substantially speeded up by changing the code to:

for ($j=0, $max = sizeof($arr), $s = ''; $j<$max; $j++)
  $s .= $arr[$j]."<br>";

echo $s;

First we need to understand that the expression $j<sizeof($arr) is evaluated within the loop multiple times. As sizeof($arr) is actually a constant (invariant), we move the cache the sizeof($arr) in the $max variable. In technical terms, this is called loop invariant optimization.

 

 

Avoid writing naive setters and getters

When writing classes in PHP, you can save time and speed up your scripts by working with object properties directly, rather than writing naive setters and getters. In the following example, thedog class uses the setName() and getName() methods for accessing the name property.

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

Notice that setName() and getName() do nothing more than store and return the name property, respectively.

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Setting and calling the name property directly can run up to 100% faster, as well as cutting down on development time.

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

 

 

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.

 

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

Produces:

INSERT INTO users (first_name,last_name) VALUES("John", "Doe")

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

$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);

Produces:

INSERT INTO users (first_name,last_name) VALUES("John", "Doe"),("Jane", "Doe")...