25 Tips to Optimize Your Code

Initially I had a chance to write code optimization techniques as a hunt of compiler construction in C++ and later I decided to do this specifically for web programing languages, as I have been working on Python, Perl and Ruby to figure out which language can be better to write applications that executes faster.
I personally found Python to be better in performance then PHP, Perl or Ruby. However If you are still a PHP developer or generally write web code these 25 tips can help you lot in terms of writing fast and memory efficient applications.

1. Upgrade Your Distribution
Simply upgrading your distribution like PHP, is without a doubt one of the easiest ways to improve PHP performance. In addition to the usual bug fixes and new features, each new PHP release ships with optimization improvements which can produce noticeable performance enhancements.

2. Use Native Functions
As much as possible, try to use native PHP functions rather than writing your own functions to achieve the objective. For example, you can use range( b, k) to get an array of alphabets starting from b to k in sequence, if it is only needed once in the script rather than declaring an array with these values in a function and returning it on its call.

3. Take Advantage of Native Extensions
PHP has long been accused of including everything but the kitchen sink, and in recent years the development team has made great strides in terms of stripping the core distribution of optional and redundant features (such as deprecating the redundant POSIX Regex library in preference of the PCRE library). Even so, the sheer number of available libraries and other extensions can be overwhelming, leading some developers to consider implementing their own solutions rather than invest the time investigating what’s already available.
For instance it might be tempting to spend a few hours writing a custom library capable of parsing XML, despite the availability of SimpleXML. Doing so ignores the many hours of troubleshooting and optimization already put into the native extensions, thereby almost guaranteeing the substandard outcome of any such custom solution. For this reason and others you should always investigate the availability of an existing library or extension before setting out to reinvent the wheel.

4. Use a PHP Accelerator
Barring outside interference, a PHP script executes after being “compiled” by the PHP engine, which turns the PHP code you’ve written into machine language, known as operation code (opcode). If the PHP script repeatedly churns out an identical result, then why not skip the compilation process altogether?
You can do exactly this using a PHP accelerator, which caches a PHP script’s compiled machine code, allowing the code to immediately execute upon request rather than after a potentially expensive compilation process.
Several opcode caching solutions are available to PHP developers, including notably APC (Alternative PHP Cache), an open source accelerator available for installation via PEAR. Another popular solution is Zend Server, which incorporates not only opcode caching, but also full and partial page caching utilities.

5. Use Late Static Binding
If a method can be static, declare it static. Speed improvement is by a factor of 4. As of PHP 5.3.0 Late static binding introduced, a new use for the static keyword, which addresses this particular shortcoming. When you use static, it represents the class where you first use it, ie. it ‘binds’ to the runtime class.
For example this will blow the code execution:

abstract class Builder {
    public static function build() {
        return new static;
    }
}
class Member extends Builder {
    public function who_am_i() {
        echo 'Member';
    }
}
Member::build()->who_am_i();

6. Performance of FOR vs FOREACH in PHP
My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy… The time difference is going to be minimal in most cases.
For some reasons I decided to do a quick benchmark run…

$a = array();
for ($i = 0; $i < 10000; $i++){
$a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v){
$a[$k] = $v + 1;
}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v){
$v = $v + 1;
}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}
echo 'Completed in ', microtime(true) - $start, " Seconds\n";

And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you’re modifying the array in the loop, it’s several times faster to use references…

7. Frequently Used Switch Cases
Keep most frequently used switch cases on the top. A switch statement is not always faster than an if statement. It scales better than a long list of if-else statements as switch can perform a lookup based on all the values. However, for a short condition it won’t be any faster and could be slower.

8. Conditions that uses = = =
Use “= = =” instead of “= =”, as the former strictly checks for a closed range which makes it faster.

9. Pass Reference to Function
Pass reference to the function if it does not affect your logic. A function manipulating the reference is faster than those manipulating the value been passed as here one more copy of the value is getting created. Especially it adds overhead when the value passed by you is a big array.
For example, let us create a function in two different way to increment by 1, each element of an array having values 0 to 99.

// passing by reference
function  computeValue( &$param )
{
// Something goes here
foreach( $param as $k => $value)
{
$param[$k] = $value + 1;
}
}
$x = array();
for( $i =0; $i<99; $i++)
{
$x[$i] = $i;
}
computeValue( $x);

// array with 100 elements each incremented by 1
print_r( $x );

The function above works faster than the function below although both will produce the same result ( increment each element of the array by 1. )

// passing by value
function  computeValue( $param )
{
// Something goes here
foreach( $param as $k => $value)
{
$param[$k] = $value + 1;
}
return $param;
}
$x = array();
for( $i =0; $i<99; $i++)
{
$x[$i] = $i;
}
// array with 100 elements each incremented by 1
print_r(computeValue( $x));

10.    Use Caching Techniques
Use cache to reduce the load of database operations as well as the script compilation. We can use memcache for the reducing database load and APC for opcode caching and intermediate code optimization.

11.    Use Single Quotes
Using single quotes ( ‘ ‘ ) is faster than using double quotes( ” ” ) if you are going to keep only the string inside it avoiding any variables. Double quotes checks for the presence of variable and adds little bit of overhead.

12.    Use Appropriate String Functions
str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.

13.    Calculate Only Once
Calculate and assign the value to the variable if that value is getting used numerous time rather than calculating it again and again where it is being used.
For example, the following will degrade the performance.

for( $i=0; i< count($arrA); $i++)
{
echo count($arrA);
}

The script below will perform much better.

$len = count($arrA);
for( $i=0; i< $len; $i++)
{
echo $len;
}

 

14.    Disable Debugging Messages
File operations are a bit expensive if you are using it quite often in code. So, if you are calling lot of custom functions to log errors and warning during your development process, make sure you remove them before you push the code to production.

15.    Use Methods in Derived Classes
Methods in derived classes are faster than base classes. For example, let there be a function in both base class and derived class for performing task1. It is named as “forTask1? in base class and “forTask1again” in derived class, so that they will not override.
Call to the function “forTask1again( )” which is in derived class will work faster than call to the function “forTask1( )” as it is from base class.

class someBaseClass
{
public function forTask1($string)
{
// perform task 1
}
public function forTask2( )
{
// perform task 2
}
}

class derivedClass extends someBaseClass
{
public function forTask1again($string)
{
//perform task 1 same as the function in base class.
}
public function forTask3($string)
{
//perform task 3
}
}

//Instantiating the derived class below.
$objDerivedClass = new derivedClass( );

// The call below works slow for task1 as it is from base class.
$resultTask1 = $objDerivedClass->forTask1( );

// The call below works faster for task1 as
// it is from derived class.
$sameResultTask1 = $objDerivedClass->forTask1again();

 

16.    JSON Vs. XML
Use JSON instead of XML while working with web services as there are native php function like json_encode( ) and json_decode( ) which are very fast. If you are bound to have XML form of data, then use regular expression to parse it instead of DOM manipulation.

17.    Use isset
Use isset( ) where ever possible instead of using count( ), strlen( ), sizeof( ) to check whether the value returned is greater than 0.
For example, let us assume that you have a function which returns an array with values or a NULL array. Now you want to check whether the returned array is with values or not, then use the following:

if(isset($returnValue))
{
// do something here
}
In this case, use the above code block, instead of the following:
if(count($returnValue) > 0)
{
// do something here
}

 

This will also be fast to execute:

// Checking if string length is 5
if(isset($foo{5}))
{
}

18.    Pre increment vs Post increment
Well, increment a certain value also have a few ways to improve. We all know that there are many ways to increment integer values such as – See more at:

$i++;
$++i
$i+=1;
$i = $i + 1;

Out of all these what way is the most efficient? In PHP, it seems like pre increment is better than the other ways of performing an increment. Its around 10% better than post increment? The reason? Some said that post increment made certain copy unlike pre increment. There isn’t any benchmark done for PHP but i found one on C++ which should be quite the same. Well, without a proper benchmark on this, i can’t really confirm this. Furthermore, it really doesn’t makes a big differences towards normal programmers but may affect those who are working towards micro optimization.  Nonetheless, many people do suggest pre over post increment in term of optimization.

19.    Absolute Path VS Relative Path
Absolute path which is also known as full path compare to a relative path which will be better for PHP? Surprisingly, it seems that absolute path is better. Compare to relative path which might just help to screw up your include and require operation in PHP, absolute path doesn’t. Well, that’s the reason why i use absolute path. But the real reason is that using absolute path eliminate the need for the server to resolve the path for you. Simply to say, do you know where the file is located when you just look at a relative path or is it faster if i just throw you the full path?

20.    Dot Vs Commas Concatenation
Between dot and commas which way do you use to concatenate between two strings/variables? I personally used dot to concatenate my stuff. Such as the one shown below:

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a.$b;

I usually do the above. Instead of this,

$a = '10 PHP programming ';
$b = 'Improvement Tips';
#10 PHP Programming Improvement Tips
echo $a , $b;

21.    use gzip compression
Use ob_start() at the beginning of your code. This gives you a 5-15% boost in speed for free on Apache. You can also use gzip compression with ob_gzhandler() for extra fast downloads (this requires spare CPU cycles).

22.    Use unset in larger scripts
unset() variables that are not used anymore to reduce memory usage. This is mostly useful for resources and large arrays.

23.    Reduce Number of Hits to DB
Try to reduce the number of hits to the database. Make queries aggregate so that you call the database less number of times. For example:

$con=mysqli_connect("localhost","username","somepassword","anydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValue( $val ){
mysqli_query($con,"INSERT INTO tableX (someInteger) VALUES ( $val )");
}
for( $i =0; $i<99; $i++){
//  Calling function to execute query one by one
insertValue( $i );
}
// Closing the connection as best practice
mysqli_close($con);

The script above is much slower than the script below:

$con=mysqli_connect("localhost","username","somepassword","anydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL" ;
mysqli_connect_error();
}
function insertValues( $val )
{
// Creating query for inserting complete array in single execution.
$query= " INSERT INTO tableX(someInteger) VALUES .implode(',', $val)";
mysqli_query($con, $query);
}
$data = array();
for( $i =0; $i<99; $i++)
{
// Creating an array of data to be inserted.
$data[ ]  =   '(" ' . $i. '")' ;
}
// Inserting the data in a single call
insertValues( $data );
// Closing the connection as a best practice
mysqli_close($con);

24.    Tune your Database
Tune your database and index the fields that are commonly used in your SQL WHERE criteria. ADOdb, the very popular database abstraction library, provides a SQL tuning mode, where you can view your invalid, expensive and suspicious SQL, their execution plans and in which PHP script the SQL was executed.

25.    For MySQL use relevant Storage Engine
Distribute your tasks into reading or writing. Use relevant Storage Engine for reading and writing. Slow writing can go to background process. Use temporary tables to boost writing.

Advertisements

Multi level navigation using backbone.js

Making multi level nested ul li navigation is not much difficult, Heres the code below to make an nested navigation.

<!DOCTYPE html>
<html>
<head>
    <title>Backbone</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="http://underscorejs.org/underscore.js"></script>
    <script type="text/javascript" src="http://backbonejs.org/backbone.js"></script>

    <script type="text/template" id="parent-template">
        <ul id='ul-<%= parent_id %>'></ul>
    </script>
    <script type="text/template" id="child-template">
        <li id="li-<%= id %>"><%= name %></li>
    </script>

    <script type="text/javascript">

    var compiledParent = _.template( $('#parent-template').html() );
    var compiledChild = _.template( $('#child-template').html() );

    var data = [
        {"id":1,"name":"one","parent_id":0},
        {"id":2,"name":"two","parent_id":0},
        {"id":3,"name":"three","parent_id":0},
        {"id":4,"name":"four","parent_id":0},
        {"id":5,"name":"five","parent_id":0},
        {"id":6,"name":"one","parent_id":2},
        {"id":7,"name":"two","parent_id":2},
        {"id":8,"name":"three","parent_id":2},
        {"id":9,"name":"four","parent_id":2},
        {"id":10,"name":"five","parent_id":2},
    ];

    var NestedView = Backbone.View.extend({
      render: function(){
        this.$el.html( compiledParent({parent_id : '0'}) );
        this.collection.each( function( model ){ this.renderElement( model ) }, this )
      },

      renderElement: function( model ){
        var ul = this.getParentUl( model );
        this.appendElement( ul, model );
      },

      getParentUl: function( model ) {
        var ul = this.$el.find( "#ul-" + model.get( "parent_id" ) );
        if( ul.length == 0 ) {
          this.appendListInElement( model );
          ul = this.$el.find( "#ul-" + model.get( "parent_id" ) );
        }

        return ul;
      },

      appendListInElement: function( model ){
        var li = this.$el.find( "#li-" + model.get( "parent_id" ) );
        li.after( compiledParent({parent_id : model.get( "parent_id" )}) );
      },

      appendElement: function( ul, model ){
        ul.append( compiledChild({id:model.get( "id" ) , name:model.get( "name" )}) );
      }
    });

    $(document).ready(function()
    {
        var elements = new Backbone.Collection( data );
        var nestedView = new NestedView({ el: "#wrapper", collection: elements });
        nestedView.render();
    });
    </script>
</head>
<body>
    <div id="wrapper">
    </div>
</body>
</html>

Facebook application’s iFrame to auto resize

If you have a Facebook iFrame application and you want to auto resize the ifram and have read Facebook’s horrible documentation for their js sdk and have tried so many different variations – all of them not working at all. This code will work for you!

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
window.fbAsyncInit = function()
{
    FB.Canvas.setSize();
}
</script>
</head>
<body>

    <!-- Some of your html code -->
    <div id="fb-root"></div>
    <script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script> 
    <script type="text/javascript">

    FB.init({
        appId: 'xxxxxxxx', 
        status: true, 
        cookie: true, 
        xfbml: true
    });

    /* Init fb Resize window */

    /* Completly removed now in JS SDK*/
    /* FB.Canvas.setAutoResize(7); */

    /* As of Jan 2012 you need to use */
    FB.Canvas.setAutoGrow(7);

    </script>
</body>
</html>