Clean and efficient coding technique in PHP

Well there are lots of discussion regarding what the actual “clean code” is. At the end of the day you can find there are mainly two criterion for clean code:


1. Efficiency: Does the code run as quickly and efficiently as possible? Does the code make the most of it’s objects and variables with maximum reuse and minimal waste?

2. Maintainability: Is the code easy to understand for other developers? Is it well planned, logical, well documented, and easy to update?

Let’s discuss the various elements comprising these two broad points regarding clean code, and example in PHP.

One way or another, all pseudo code is eventually converted to machine code. This code will occupy some finite amount of memory. Some languages, such as Java and the .NET Framework first product IL (Intermediary Language) code before producing machine code. In PHP, there are a few key ways to minimize the amount of memory and machine code overhead generated by your application. The best place to start the discussion is with loops and conditional statements.

Case Statements – A case statement produces roughly 1/5th the amount of machine code as an if/else structure that completes the same task. Use case statements whenever possible. The difference in memory overhead between these two statements is fairly nominal, but the case statement is more efficient to some small degree.

Loops – Loops vary more drastically than conditionals due to the nature of the operations they perform. PHP offers a number of loops. When deciding what type of loop to use, consider the operations taking place. Let’s look at the following example, where we have a query that will return around 2000 results.

$r = mysql_query(‘SELECT * FROM tablename LIMIT 1500′);
//First option
for ($i = 0; $i < mysql_num_rows($r); $i++) {
print mysql_result($r, $i, ‘Col1‘).mysql_result($r, $i, ‘Col2‘);
}

// Second option
while (($row = mysql_fetch_assoc($r)) !== false) {
print $row[‘Col1‘].$row[‘Col2‘];
}

The first option requires simply one scalar variable used as a counter for iteration, using a lightweight access method to read buffered data from a result handle. The second example uses an array constructor function to build an array and evaluate it’s contents on each iteration, and then references the array two times per iteration. The bottom line is “SECOND OPTION” runs significantly faster. It has lower memory and machine code overhead.

Best Practices

It is subject to much debate and a variety of standards. Let’s start the example with single quotes (‘) vs using double quotes (“). The PHP parser treats these two token identifiers very different. PHP treats anything inside a matching pair of single quotes as a string literal and does not parse the contents of that string. However, PHP treats anything inside a matching pair of double quotes as string data and parse the contents of the string. This can result in major performance disparities in a page with extensive data output. Let’s test printing 1,000 lines of output in the following two methods:

// First Option
print “Name : $name. Address : $add. Email: $email.”;

// Second Option
print ‘Name :’.$name.’. Address : ‘.$add.’. Email ‘.$email.’.';

Can you imagine second option run 30% faster than the first one. The big difference between these two examples is that in first option PHP is required to full parse the contents of the string. Second option is the equivalent of concatenating seven string literal values together and printing them out, which requires no actual string parsing.

Other “best practices” that are more thoroughly documented include:

* Using a consistent and logical naming convention for objects, functions, classes, etc.
* Commenting code line by line (or as near to line by line as is needed to clearly explain what operations are being performed).
* Indenting code to reflect the beginning and ending of statements (particularly statements enclosed in curly braces).
* Organizing files in a logical directory structure with easy to understand directory and file names.
* Making code as modular and reusable as possible i.e use functions if the same code is going to be used in many places.

These things may seem obvious to seasoned programmers, but for a lot of beginners, these are things that are often overlooked in haste.

7 thoughts on “Clean and efficient coding technique in PHP

  1. Topbit

    echo ‘Name :’, $name, ‘. Address : ‘, $add, ‘. Email ‘, $email, ‘.';
    // no concatenation involved

    I wouldn’t bother rewriting it though if I had originally written it another way – chances are the time spent editing it would be more than the time a CPU takes to run it 10,000 times. CPUs are cheap – I am not.

    Such nano-optimisations are inevitably blown away by several orders of magnitude with poor algorithm choices, database or file-system accesses (unless they are perfectly optimised – which isn’t going to happen anyway) or just using a library or framework that takes more time than it could, but you use it because it will save you a few minutes (or hours, or days) development.

    As always, write clean, secure, and easy to maintain code first. Then, and only if it is not fast enough, look for the best thing to optimise – and just do that. Rinse, and repeat, if required.

  2. Michael

    I would rather bug the ppl writing the interpreter then take the effort to bring the ‘best practice’ of rewriting switch to if else statements.

    As noted above: write it cleanly and then profile and then take action accordingly. Practice also shows that when profiling the ‘hotspots’ or bottlenecks are usually not in the place one expects. In short don’t micro-optimize things.

    “Commenting code line by line (or as near to line by line as is needed to clearly explain what operations are being performed).” I can’t disagree more. comment blocks of code; this way it ensures that your code is organised. This is because it forces the programmer to make one block of code do one thing(and do it well) and thus leave your code untangled. And as you don’t comment lines it creates a limit to the amount of things that one line of code does. This removes (old) C++ alike-style line of code where a shitload of operations is done and everyone has to look (adleast) twice(including the one who wrote the line) to figure out what’s going on.

    “Making code as modular and reusable as possible.”

    Is dangerous to say too; you can go overboard. Tbh I would go with something along the same lines as profiling. See that it repeats itself first and then refactor it out. Now I know PHP-refactoring support is limited at this time but I’m sure it’s there ‘tomorro’.

  3. Ellis Geeklab.net

    For the switch() – the code is a lot easier to read in my opinion. But I have seen bench marks showing that switch is slightly slower and vice versa.

  4. pusp jodhi

    i want to learn the standerd coding style in php. please if it can be possible please forward me

  5. Agreed with pretty much everything but just wanted to add that in many cases I use classes instead of functions so the code is better organized and clearer.

    For example instead of calling a function such as:

    get_customers_profile();

    I would use:

    $customer->get_profile();

    Or if I use a framework (I usually do) such as Codeigniter:

    $this->customer->get or get_profile.

    Much easier to keep the code clean and organized when it’s in classes (same idea with folders).

    Nice blog, keep it coming! :-)

  6. nice articvle

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>