Three most effective ways to boost performance

When thinking about performance, there are three key things that you could do that work wonders on your performance. In this entry we are going to explore them.

Loops

A loop is a fundamental construct in all major computer languages and for a good reason too. You wouldn’t be able to do much without it. It’s uses are varied including:

  • Core part of Divide and Conquer algorithms
  • Unpacking results from database
  • Acting on multiple inputs
  • etc

Their prominent place in our world is not carte blanche to spate our code with it, regulation is key! The reason for that lies in how running time relates to loops.

Without going into details, it suffices to say that a simple loop takes n time to complete, a loop nested within it would take n^2 time by the time you get to another loop the time is now n^3. At this level of complexity it would be impossible to run the program in any kind of production system.

As such we need to find ways to either eliminate loops, make them run in a serial fashion or use recursive methods.

Here is an example, suppose we have an array of names.


$names = ['Rachel', 'Ben','Justin','Gloria'];

We would like to attach information about say gender and nickname to the data.

The most obvious way of doing it would be

foreach($names as $name){
        $name['gender']= determineGender($name);
}
foreach($names as $name){
        $name['nickname']= determineNickname($name);
}

This code is not too bad and in fact could potentially work if data set remains small, however we can make it much faster by simply combining the two operations as such

foreach($names as $name){
        $name['gender']= determineGender($name);
        $name['nickname']= determineNickname($name);
}

Minimize calls to external systems

Modern applications requires an entire host of supporting services to make them work. The most common include:

  • Databases
  • Search engines
  • File systems

What may seem blazingly fast may not work so well when your system needs to scale.

In the example below we think of a situation where we retrieve names and then display them alongside with people of a related gender.


$names = DB::findByName("Julia");
foreach($names as $name){
        $names['gender']=determineGender($name);
        $names['related']=Db::findByGender($namesWithGender['gender']);
}

In the above case we are calling the database each time the loop runs. For large loops this process would become more expensive.

Instead of that mess, we instead need to make all our database calls first and then bring in the extra information.


$names = DB::findByName("Julia");
$femaleNames = Db::findByGender('female');
$maleNames = Db::findByGender('male');
foreach($names as $name){
        $names['gender'] = determineGender($name);
        if($names['gender']=='male'){
                $names['related']=$maleNames;
        }
        else{
                $names['related']=$femaleNames;
        }
}

While a tad more complex, the above code greatly minimizes outside calls.

Cache cache cache

Never do the same work more than once! If it can be cached, let it be cached.

Even light tasks can be cached for incredible performance. When your App’s popularity skyrockets you will be thanking the code gods for the blessing of caches.

Some candidates for caching include:

  • Database results
  • Computation results
  • HTML rendered

Using an external service has to be balanced with the cost of calling the said service. Sound judgment and good engineering taste will help you determine the best cause of action.

Should you decide to cache, I highly recommend the popular service memcached.

Have you ever had performance issues on your own application? How did you deal with it? Tell us in the comment section below.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

One design to rule them all

 

This post is a continuation of Metrics on quality of software

As developers we like our solutions cut and dried. For every problem there is a tempting desire to believe that there exists one perfect solution if only we look hard enough.

Yet we have already talked about the futility of such a belief. The tl;dr version is that you only fully understand your project once the code committed, not a moment before.

This may not be a problem if a single optimal design existed, but the reality is that the design space is exceedingly rich. Wether you chose to believe it or not, there is almost certainly a better design than what you just committed.

With this in mind then the goal is not to find an optimal solution but to evaluate trade offs for what best serves your purpose. To that end I present a Metrics on quality of design.

Complexity

All good things come from the heart, and as we all know managing complexity is at The heart of software engineering

From the lofty heights of this generalities you may be wondering how do you measure complexity in software. Well there are a myriad of standard software metrics but almost all of them require the project to be done before you can apply them. I think the most intuitive is to simply ask yourself.

    Does this design allow the developer to concentrate only on this part without knowing any other part of the project?

Make a habit of asking yourself this question regularly as you are spitting out the code.

Maintenance

You can talk about speed or maybe even Big Omega but as far as I know, none of this ideas owns a shotgun. Do you know who owns a shotgun? The developer who is going to maintain your code, and yes they know where you live!

In your design always assume that the next developer to touch the code lacks any contextual knowledge. As such the design should be well documented and even better, be rich in the quality of affordance.

As a rule of thumb remember

    It is easier to make changes in your code during development than it is during maintainance.

Reusability

Software reuse is a very old and a very successful idea.

We routinely reuse various software components in writing our code, math function, string manipulations etc.

Yet it’s a rare breed that writes their own software in a way that can be reused! Be the change we all want to see.

Dependency management

Remember back when we talked about trade offs? Well here we have one in practise. To reuse code means to increase the dependency between your code and the code you are reusing. Yet this is a necessary part of advancing your software.

    When we don't control the dependencies in our code, the second law of thermodynamics comes into effect in its full glory. 

As with all necessary evils, we need to keep dependencies to a minimum and for large projects, a clear interface should be defined and the dependency fulfilled at compilation.

Check this awesome article by Martin Fowler for more context InversionOfControl

Extensibility

Have you ever made a change to the mapping area of your application and have the login area explode? This has happened to one of my colleagues and needless to say, the entire code base had to be scrapped!

Changes to your code need not be catastrophic, in fact with a little forethought your design should be able to handle such changes gracefully.

    Welcome changing requirements, even late in development. Agile processes harness change for the customer's competitive advantage.
    ~Agile manifesto

To do this make sure areas most likely to change are properly insulated and interfaces defined.

Essential ism

    The wisdom of life consists in the elimination of non-essentials
    ~Lin Yutang

Mr Lin would have made for an excellent developer!

Most code written is simply fluff, this wouldn’t be a problem except for the fact that the extra code adds very little value yet manifests its full weight in maintenance costs. The single most effective way of dealing with it is to cut it out.

Standardize

Whenever standardization is mentioned, developers get belligerent perhaps under the assumption that they are being treated as interchangeable cogs.

But the truth is, standards confer leverage, by using standard tools and practises to mill through the mundane bits, you free up the energy to exercise creativity on what is truly important in your project.

Have you come across a good design lately? Do you feel that the developer took into consideration the principles mentioned above? Tell us what you think in the comment section below.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Name well or go home

Throughout our programming education, we are typically taught how to communicate with the computer. We master the art of bending the black box to our will! But how many teachers actually emphasize the other use of code? Yes each piece of code you write communicates not only with the machine but even more importantly with another human. Possibly the rest of your team or the open source community or maybe even the future you.

While there is a lot to be said on making your code communicate better, the best place to start is how you name entities in your code. The information you pack into each name will be seen everywhere the entity is used. This makes a good naming structure a valuable investment in your code.

Think of each name as an expressive albeit tiny comment on what is currently going on in your mind. By looking at the name, the reader should be able to get context of what is happening.

With that said, let us look into some ways of improving the naming convention of your code.

The curse of the generic name

Bill gates is famously quoted to have said

    "I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it."

Unfortunately too many of us only read the lazy person bit and take that to heart. Using variable names such as id, retval say nothing about the code. But say a lot about the lethargy of the developer who wrote it.

//Sample 1

$id = \Input::get('id');

//Sample 2

$user_id= \Input::get('id');

Of the two samples above, which one do you think is clearer? Did you get any context information from Sample 1? What about Sample 2?


//Sample 1

$retVal= (PROFIT * 0.7);

return $retVal;

//Sample 2

$incomeAfterTax = PROFIT * TAX_RATE; 

return $incomeAfterTax;

What about the above example?

Precise names work magic on your code.

The only instance which you are allowed to use generic names is when you are using iterators


for ($x = 0; $x <= 10; $x++) {
    //Do something well named
    } 

Be explicit

In applying the principle dictated above, we may miss the entire point by giving names based not on what the code does but in our understanding of it. This insidious action can render our code even less comprehensible than before. Take a look at the example below.

$cleanStr=runCleanUp($str);

Did you understand how the $str is getting cleaned up?

$cleanStr=removeUnprintable($inputStr);

What about now?

Crucial information

In some cases you might find yourself in a situation where the variable represents some special information. This can be:

  • Unit of measurement
  • Data type
  • Security issue
  • Regulatory issue
  • etc

In such cases find a way to include that info


$cost = $vol * 95;

Contrast that with


$totalSale = $vol_litres  * PUMP_PRICE;

Naming scheme

Most languages have a naming scheme, in PHP we has PSR-4 Python has PEP 8 and so on. It’s important to chose your favorite and stick with that.

Thankfully most editors ship with a style checker that can help enforce this displine.

Above are just a few of the naming rules you can use to make your code that much better.

What conventions do you use in your own projects? Tell us in the comment section below.

Facebooktwittergoogle_plusredditpinterestlinkedinmail