Tuesday, 6 September 2016

Improve PHP Performance

In this lession i'm going to tell you some useful tips and techniques to improve and optimse your php code. These tips are basics and some techniques are already done in frameworks.

PHP Tips & Tricks


1. Ternary Operators : A ternary operator is a different way to layout a simple if else statement.We'll just use a simple check to see if a GET parameter is set and not empty, if it is we will default to the word Hello, otherwise use the value that was set as the GET parameter.

$name = (!empty($_GET['name'])? $_GET['name'] : 'Hello');

2. echo vs print : PHP sting functions to printing output into browser and we are often using print() and echo() function.Print() will return an integer value.so print() can used as part of expression which more complex.echo() is able to accept more than one parameters all at once and it doesn't have any return value.

<?php
print() 'string 1';
echo 'string 1';
// using some parameters
echo 'string 1', "string 2", '...';
?>
echo is faster than print 

3. Loop in PHP : Dont use the count function on loop statement ex. for($i = 0; $i < count($array); $i++) it's slow down the process because checking every time count on a loop.

<?php
$max = count($array);
for ($i = 0; $i < $max; $i++)
//is faster than
for ($i = 0; $i < count($array); $i++)
When checking the length of strings:
Use isset where possible in replace of strlen. (cite)
if (!isset($foo{5})) { echo "Foo is too short"; }
//is faster than
if (strlen($foo) < 5) { echo "Foo is too short"; }

4. Single Quotes vs Double Quotes: single quotes and doubles quotes are easy to use but using a right quotes for your need boost your application.

<?php
  echo 'hello world';
?>
<?php
  echo "hello world";
?>

5.Incrementing in PHP: 

Use pre-incrementing where possible as it is 10% faster.

++$i;
//is faster than
$i++;

Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

6. true vs TRUE : This is because when looking for constants PHP does a hash lookup for name as is & since names are always stored lower cased, by using them you avoid 2 hash lookups. By using 1 and 0 instead of TRUE and FALSE, can be considerably faster.

7: Use isset() instead of strlen() function:


<?php
$str = "45e23";
if (!isset($str{5})) {
    echo 'String must be at least 5 characters<br />';
}
if (strlen($str) < 5){
    echo 'String must be at least 5 characters;
}
?>



isset() take little more time than strlen() because isset() is a language construct.

8. Omit the closing php tag:


<?php

echo "Hello";

//Now dont close this tag

This will save you lots of problem. Lets take an example :

A class file super_class.php
<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}
?>


//super extra character after the closing tag

Now index.php

require_once('super_class.php');

//echo an image or pdf , or set the cookies or session data
And you will get Headers already send error.Because the super extra character has been echoed , and all headers went along with that. Now you start debugging. You may have to waste many hours to find the super extra space.

Hence make it a habit to omit the closing tag :

<?php
class super_class
{
    function super_function()
    {
        //super code
    }
}

//No closing tag
Works better.

9. Dont use require , include , require_once or include_once: Don't include script files on top , like class libraries , files for utility and helper functions etc like this.

require_once('lib/db.php');
require_once('lib/common.php');
 
require_once('helpers/some_library.php');

Best way to use it. Write up helper functions to include things more easily. Lets take an example :

function load_class($class_name)
{
    //path to the class file
    $path = ROOT . '/lib/' . $class_name . '.php');
    if(file_exists($path))
    {
        require_once( $path ); 
    }
}
 
load_class('db');
load_class('common');

Benfits of using load class:

It will search multiple directory same time.
Change the directory containing class files easily , without breaking the code anywhere.

10: Class Autoloading: We include a large number of files in our top header scripts. But what if we have a very large number of classes that we could potentially use within one or many sections of our code.So instead of including classes that might not get used, or we might remove later, we can employ class autoloading.autoload classes will notify or throw an error that we've not included the class file.PHP function spl_autoload_register() we used for the autoloading the class files.

function loadMyClass($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
}

spl_autoload_register('loadMyClass');

The first parameter of the function is specified the class name.

spl_autoload_register(function ($class){
    echo 'We are loading class: ' . $class;
    include_once('classes/' . $class . '.inc.php');
    echo 'Class loaded.';
});


If you like the post please share and comment.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts