Performance Friendly PHP

June 12th, 2008

As you grow into programming, you can pick up some poor habits along the way. These habits produce the same output, but when used in large projects could end up causing some performance headaches in the long run, causing you to get mentally spanked for not paying attention when reading this article!

So to save your ass, I’d like to shed some light on good versus bad methods. You may disagree with some methods because they may not improve readability of code, and that is your choice, but the ultimate aim of this article is to promote the most performance friendly method for a given situation.

Strings on Multiple Lines

If you work with PHP, sooner or later you will need to manage a multiple line string in code (whether it be for outputting text, or creating a SQL statement string). If you need to create a multiple line string, my advice is to use multiple lines within the ONE string.

Eg: Don’t do this:

<?php
$sql_insert_string = 'SELECT id, name';
$sql_insert_string .= 'FROM products';
$sql_insert_string .= 'ORDER BY name ASC';
?>

(performance unfriendly: PHP has to allocate memory for three strings and concatenate them)

Or this:

<?php
$sql_insert_string = 'SELECT id, name'
. 'FROM products'
. 'ORDER BY name ASC';
?>

(performance unfriendly: Even though this looks like one long string, PHP is really dealing with three strings and has to concatenate them to form the one string)

Instead, do this:

<?php
$sql_insert_string = 'SELECT id, name
FROM products
ORDER BY name ASC';
?>

(performance friendly: PHP has one string to deal with, single memory allocation, no concatenation)

Use Single Quoted Strings

I’m sure you know about PHP’s nice and friendly way of allowing you to put variables directly inside double quoted strings like this:

<?php
$years_old = 21;
$one_liner = "Hey good lookin, you must be $years_old this year";
?>

(performance unfriendly: unnecessary overhead)

This seems nice and handy I know, but for PHP, this means that ANY string with double quotes has to be searched for potential variables = unnecessary overhead.

Instead, stick to the single quote method. As I also work with VB.NET (where there is no double quote support for strings) this wasn’t a hard one for me to adjust to, but if you’re starting out, it’s important to not get into the bad habit of using double quoted strings if you can avoid it. You might think the overhead marginal, but add up all the double quoted strings in your ever-growing application, put your application under heavy load with shitloads of users hitting your webserver and you’ll be wishing you had written your strings in the single quote method.

This is the better version:

<?php
$years_old = 21;
$one_liner = 'Hey good lookin, you must be '.$years_old;
?>

(performance friendly: No double quotes here, yay!)

I can attest to this being true. I had a project a year or so ago that dealt with heavy mathematical operations (luckily the mathematical operations were already written and I just had to translate them to PHP). I had the bad habit of always writing variables within double quoted strings for various output. When it came time to analyse the performance, the client wanted every minisecond he could get. I had to find ways to knock a few seconds off execution time. The first thing I did was a mass find-and-replace operation to convert double quoted strings to the single quote method (not an easy operation), but when I was done we shaved a second off. That one second proved to me just how important this method is. Imagine an extra second load time for users when your webserver is under load :-/

Note: This same principle applies to array indexes:

<?php
//if using string indexes, do it like this:
echo $date_array['january'];
//not like this:
echo $date_array["january"];
?>

String Concatenation and Output

This is a pretty cool trick I didn’t know about until recently, but you can use commas to concatenate strings in PHP and it provides a performance benefit.

For example:

<?php
//while this looks like a single line of output:
echo 'SELECT id, name' . ' FROM products' . ' ORDER BY name ASC';
//to PHP it actually translates to:
echo 'SELECT id, name';
echo ' FROM products';
echo ' ORDER BY name ASC';
?>

(performance unfriendly: even though this looks like one long string, PHP is actually dealing with three separate strings here, and sending all three strings to output as shown in the translated section …hence unnecessary overhead)

Instead, use commas:

<?php
//this looks like a single line of output:
echo 'SELECT id, name', ' FROM products', ' ORDER BY name ASC';
//it actually translates to one line of output for PHP:
echo 'SELECT id, name FROM products ORDER BY name ASC';
?>

(performance friendly: PHP has one string to deal with, single memory allocation, no concatenation)

Choice of Functions

Always refer to the official PHP manual when confronted with a choice of potential PHP functions for a given situation. Many functions exist that appear to do the same thing, but if used unnecessarily can lead to unnecessary overhead/confusion in your applications.

For example, you will probably get some advice to look at using preg/ereg functions in PHP whenever you ask about string replacements, but if you need to do a simple string replacement (Eg. replace all ‘http’ with ‘https’) use the str_replace function. Only use the preg/ereg functions when you need to involve regular expressions …that is their purpose. And str_replace is for simple string replacements.

The Importance of SEO

June 9th, 2008

I was asked today about why ‘just having a website’ is not enough to be successful online. The question came up after I was talking about a seminar I attended last year with my father. The seminar was an American based company successfully selling website services (of course they didn’t market it like this, but that’s all they were essentially doing) selling a website that they’d create for you, providing you with a specific product driven website that would ‘definitely make you wealthy beyond your wildest dreams’.

Now I say ’successfully’ because more than half the audience was sold on their little scam. And for big money too. We’re talking upwards of $12,000 for each sale. You might think crazy price, but for a fully product driven website, with the company holding your hand the whole way, that’s probably about the right price. The only problem is they were hinting at guaranteed success, and failed to mention how competitive the search industry is for any common product driven website. Sure, hand over your hard earned cash, get a website developed, but then what? How is anyone going to find your site over the thousands of other sites all similarly produced?

The truth is search engine marketing is a massively important part of the equation, and I’d  say you need to allow more than half of your initial project budget and time to search engine activities for the first year, otherwise you can expect to be getting minimal, if any, traffic to your fancy site. I won’t go into specifics about search engine techniques, because honestly I’m still learning myself (and it is a continuous learning curve), but I will be documenting my progress as I learn and succeed, so keep tuned. My point is simply to make you aware of scams like this one I witnessed, and to be very wary of anyone selling you a website that fails to mention the importance of ‘being found online’. If they don’t mention it, YOU bring it up. It’s your money and your future success. Be smart, ask the questions, analyse the answers. If you’re unsure about the answers you get, take your question and the answers you’ve got to the top search forums (type ’seo forum’ in google) and see what the experts have to say about your situation. You’ll find the nice guys more than happy to comment honestly and openly. Don’t ever be taken for a ride …and always remember that the people you deal with are often professional salesmen :-)

CSV Data Generator

June 4th, 2008

I’m in the process of creating a csv import application for employee data among other things, so I needed good quality test data. Instead of writing a few lines of test data myself, I thought I’d check if any free applications existed to do the work for me. I’m into free applications that I don’t have to download, so the search was on, and I’m happy to say I didn’t have to look very far.

I found this free little tool for generating different types of data online:

(http://www.generatedata.com/#generator).

I just plug in a few options and this generator gives me as much realistic data as I need to properly test my csv import application. Saves me more than a few minutes writing test data myself. Useful for load testing as well. Generate a few thousand lines of csv, import it to your database and test away. Of course, you can use MySQL functions to help generate a heap of INSERT statements as well, but this is another way :-)

The Importance of Coding Preparation

June 4th, 2008

Some call it coding preparation, others will call it planning and design, but we’re talking about the same thing. The more I code, the more I see professional programmers who just want to code. They don’t care if the design is complete. After all, they have enough info to get started right? They have the coding bug. I know because I have the same bug. Coding is our high. Solving small or large problems in code form gives us a buzz. You are God of the moment. Just like any other high, it can entice you into doing something too quickly without thinking it through.

The problems come when you leave the small problems and move into medium-large scale problems with lots of interrelated subsystems all talking to each other. Or, more importantly, when you have a system with base classes and you start the coding of the base classes too quickly. End result - disaster! Coding is just like real world construction: If your foundations are crap, guess what? The final product (if you ever make it to a final product) will be flimsy at best. It (your application) will either fall over or will be subject to criticism for the rest of its short life because of what we call incomplete coding preparation.

Still feel like rushing into that programming? If you do you’re a knob (politically correct term for you morons that are giving programmers a bad name by jumping into programming too quickly, then blaming the designers and everyone else when things go to shit)

Being what I consider a good programmer means having the ability to read design documents and being critical of them. Don’t take the attitude that if the coding screws up, we can trace it to the design documents, so the designers will be to blame, not me. That’s the quickest way to failure. Instead, stand up, approach the designers and tell them of the errors or any questions you have. Feel unsure about a section of the design? Ask them! Think of it like this: If you, a professional programmer, cannot understand the design document, then the design is flawed.

A key concept you need to understand early in your programming life is that the overall goal of planning and design is to reduce risk. Asking questions of the design, if you (the programmer) don’t understand something, is all helping to minimise the risk and ensure the project’s success. Your project’s preparation needs to focus heavily on improving the planning and design so that the clear direction follows through to the programming stage. Ensuring good communication between design and programming is imperative to your project’s success and the wellbeing of everyone involved.

I know, I know, some programmers are out there reading this and saying to themselves “but my boss wants things done quickly and we don’t have the time.” Bad attitude and wrong decision.

Firstly, good design might be hard to master at first, but once your designers get in the groove of turning out quality well thought out designs, everything runs smoothly. The programmers can’t stuff anything up if the design is bulletproof, and if they do, they need a boot up the arse so they begin to follow the good direction of the design to a tee. What follows is a well oiled application making group of individuals that respect each others work and produce good results, which in turn gives the company a better reputation for quality work. The point is, good design may take time, but it takes less time than bad design stuffing up the programming stage, which will end up taking a LOT more time to fix and re-test. So if your boss doesn’t understand that, request a meeting and let them know, and if nothing changes, find a new boss because you deserve better :-)

Useful MySQL Fact: Get Random Record(s)

May 25th, 2008

There may be times when you need to select a single random record from your mysql table. Now you could just select a bunch of records from mysql, then do the random operation in php from the results array, but why use the overhead? MySQL has a random function built in and with this logic you can select a single random record from your table:

SELECT id, name
FROM products
ORDER BY RAND()
LIMIT 1

This will take a single random entry from your products table. Done. Using similar logic (just changing the LIMIT) you can of course get a larger random distribution, if say you wanted to list ten random products.

Very Impressed With New Wordpress 2.5

May 25th, 2008

The title says it all …Vanessa told me that our boss Darryl really likes the new wordpress, so seeing I didn’t even know there WAS a new wordpress I thought I’d check it out. The old 2.0 version just didn’t have what I was looking for 6 months or more ago, so I made my own CMS site (which I’ll be documenting as a ‘how to’ on this site over time), but now it’s safe to say this new version of wordpress ROCKS!

The admin design has had some serious modifications to vastly improve usability. No more menu clutter. Smart use of ajax technology where necessary. But I just can’t get over how clean and professional the whole package looks. Things are just intuitive. And the really cool part is I can use Windows Live Writer to write blog posts from my desktop without even needing to be logged into the website (not a huge bonus but still pretty cool)

I’d seriously recommend checking out wordpress’s latest and greatest stable offering. The interface is really second to none. Thanking you wordpress!

Singleton Pattern

May 17th, 2008

The singleton design pattern is used to ensure a class has only one instance, and that global access to that instance is available. In other words, it restricts instantiation of a class to one object.

When I first read this concept I just didn’t get it (I’m a bit slow). But it’s really pretty simple. You just have to know your terms. A class defines the structure of an object, and to use that class, we instantiate an object of the class. So take the following php:

<?php
//create an instance of the Product class
$product_object = new Product();
//print the product's name
echo $product_object->product_name;

//create another instance of the Product class
$product_object2 = new Product();
//do other stuff
//...
?>

In this example, ‘Product’ is the class and ‘$product_object’ and ‘$product_object2′ are instances of the Product class.

We use the singleton pattern by creating a class with a function that creates a new instance of the class only if one does not exist. If an instance does already exist, it simply returns a reference to that object. This ensures you only have one instance at any one time, hence singleton.

So in the above php for example, if our Product class used the singleton pattern, ‘$product_object’ and ‘$product_object2′ would in fact be referring to the same instance of the Product class.

Why is this useful?

Well firstly I imagine this would use less system resources. If it’s only ever referencing one instance, memory usage would be kept to a minimum, so one could argue a performance advantage.

Secondly I could see this pattern useful in complicated systems where you need a be referencing a single object at any given time, perhaps a User object, to coordinate actions in different parts of the system, or sub systems. A user object is often referenced in many different parts of the system, so always referencing the one instance would be beneficial.

Real world example

Here is some example code from the PHP manual on how to create a class that uses the singleton pattern:

<?php
class Singleton{
	// $instance holds a single instance of the object
	private static $instance;
	// private constructor
	private function __construct(){}
	// the getInstance() method returns a single instance of the object
	public static function getInstance(){
		if(!isset(self::$instance)){
			$object= __CLASS__;
			self::$instance=new $object;
		}
		return self::$instance;
	}
	public function displayMessage(){
		echo 'I am a Singleton';
	}
}
$singleton=Singleton::getInstance();//return a single instance of the object
$singleton->displayMessage();// display message
?>

And here is another useful example I found that you can use that is more animated …run this and you’ll see the singleton output inform you that only one instance exists at a time :-)

<?php
echo '1:';
$user_1 = CurrentUser::singleton();

echo '2:';
$user_1->counter();

echo '3:';
$user_2 = CurrentUser::singleton();

/* Singleton Class: CurrentUser */
class CurrentUser {
    // Hold an instance of the class
    private static $instance;
    private $counter = 0;

    // A private constructor; prevents direct creation of object
    private function __construct() {
        echo 'Constructing CurrentUser';
    }

    // The singleton method
    public static function singleton() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        } else {
            echo 'CurrentUser already exists';
        }
        return self::$instance;
    }

    public function counter() {
        echo 'CurrentUser -> counter = ' . $this->counter;
        ++$this->counter;
    }
}
?>

(original source)

Design Patterns Defined

May 17th, 2008

A design pattern is a software engineering terms and is used to describe a reusable solution to solve common problems in software design. A design pattern doesn’t provide you with code per se, but is more a method of development, or template, to solve your problem.

Design patterns speed up the development of a project by providing a proven and tested way of doing things. Reusing design patterns in your project helps to prevent any unforeseen problems, and provides a common ground for developers working on your project who are familiar with the patterns. This can help to improve your code readability and consistency of methods, which all help to provide a good software product.

Imagine you introduce a new developer to your project. If your current developers can say that the X part of the system uses the Decorator pattern, both developers have just saved a lot of time in teaching/learning curve, because the developers know what that means. It’s their ‘geek speak’ and allows them to explain a somewhat complicated concept very quickly.

My point is, if you want a future in the software industry, you need to be fluent in this geek speak so that you too understand these terms for quick introductions to new or old projects. What follows is examples of the common design patterns in software engineering with easy to understand examples for each pattern to help you learn and understand the concepts quickly.

Decorator Pattern

May 17th, 2008

The decorator pattern allows us to extend (decorate) the functionality of a class at runtime (wikipedia).

I was largely self taught in programming, so this description sounded just like classes, subclasses, and the whole concept of inheritance, but this is a different concept (related, but different). A good example I found made this easier to understand, so I thought it relevant to share the ‘easy to learn’ stuff around ;-)

The decorator patterns works by creating a ‘decorator’ class that wraps the original class. This effect is achieved by passing the original object as a parameter to the constructor of the decorator class. You specify any extended (or new) functionality in the decorator class, and any original class functionality can be called as usual (don’t worry, there’s a good example to follow soon).

So straight away I’m asking:

“Why the hell would I want to do that when I can use inheritance and have a neat class/subclass solution that I am more comfortable with?”

and

“What is the difference between the decorator pattern and standard inheritance?”

Well, inheritance happens at compile time, whereas decorating provides the original classes with the additional (decorated) functionality at runtime.

Wow, that sounds real important. Who cares! I use PHP, compile and runtime mean bugger all to me. Give me a reason why I would use this method! It took this example to finally get the message across to me :-)

Real world example

“As an example, consider a window in a windowing system. To allow scrolling of the window’s contents, we may wish to add horizontal or vertical scrollbars to it, as appropriate. Assume windows are represented by instances of the Window class, and assume this class has no functionality for adding scrollbars. We could create a subclass ScrollingWindow that provides them, or we could create a ScrollingWindowDecorator that merely adds this functionality to existing Window objects. At this point, either solution would be fine.

Now let’s assume we also wish the option to add borders to our windows. Again, our original Window class has no support. The ScrollingWindow subclass now poses a problem, because it has effectively created a new kind of window. If we wish to add border support to all windows, we must create subclasses WindowWithBorder and ScrollingWindowWithBorder. Obviously, this problem gets worse with every new feature to be added. For the decorator solution, we need merely create a new BorderedWindowDecorator—at runtime, we can decorate existing windows with the ScrollingWindowDecorator or the BorderedWindowDecorator or both, as we see fit.

Another good example of where a decorator can be desired is when there is a need to restrict access to an object’s properties or methods according to some set of rules or perhaps several parallel sets of rules (different user credentials, etc). In this case instead of implementing the access control in the original object it is left unchanged and unaware of any restrictions on its use, and it is wrapped in an access control decorator object, which can then serve only the permitted subset of the original object’s interface.” (wikipedia)

Downgrade Gracefully

May 7th, 2008

We often rely on external connections in our coding. One such example is a connection to our database. Others might be SOAP connections, or any external API like Facebook.

Do you know what happens to your code if the database becomes unavailable, or the external API just drops off the face of the net? I mean, you’ve taken the code examples from someone else that had “or die(’no database connection’)” …but have you actually tested what this does and how it looks to a user should this connection become unavailable?

The best thing you can do is provide incorrect database parameters to your website and sit back and just see what happens. Try an incorrect host, then try incorrect login details to the correct host. Then try the wrong database name. Try it all, and see how your application performs. You should always present your USER with a pleasant message, and not some PHP generated error message with half your page cut off from a loading problem. So either create a page dedicated to such situations where you can redirect to in these instances, or just make sure you present a friendly error message on the page where the problem occurred, ensuring the rest of the page design doesn’t get cut off unexpectedly thanks to the error that’s occurred.

Doing this is important for your users. If they see a bad error message instead of your site, they might not come back. And also importantly is the type of error messages you show in your coding. PHP fatal errors with databases might show your database name, and login details. We wouldn’t want to give a hacker the favour of all the hard work would we? So play smart and handle your errors!