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

Go deeper to become better

You have been assigned a new and foreign task, say you need to ensure that each new registered user gets a nice welcome email. Your platform of choice is laravel but you have never really worked on this task before. What is the first thing you do?

If you are like most people you simply look up the documentation and copy paste something like this to your code.

Mail::send('emails.welcome', $data, function ($message) {
    $message->from('us@example.com', 'Laravel');

    $message->to('foo@example.com')->cc('bar@example.com');
});

You would then go right ahead and modify the code to fit your own context say

$data= ['user'=>Auth::user()];
Mail::send('emails.welcome', $data, function ($message) {
    $message->from('admin@chenchatech.com', 'Web admin');

    $message->to($data['user']->email);
});

And you are done! Now just stick this in the registration process and all is dandy. So far so good, you needed to deliver fast and you have, but is that it? Do you even understand what is going on?

Unfortunately this happens so much in programming that it’s an accepted practise and for good reason too. It’s quite easy and even profitable to depend on other peoples knowledge of fundamentals. We do this all the time and tell ourselves that later we shall take the time to go back and understand it but do we ever do it?

When crunch time comes knocking and you need to implement a novel use case in a week, you will need months just to master the basics, so why not start now?

So next time you come across a new problem how do you handle it?

First and foremost break the copy and paste habit, instead think about new concepts as a mental structure to be anchored upon existing knowledge. If said knowledge doesn’t exist, then build that!

Secondly try to understand the historical context, in our example above, try to see not just how laravel does it but how is it implemented in PHP? On what RFC is it based?

Thirdly think about the concept as it relates more generally in this case we are thinking about communicating with a just registered user. This might even give us insight into a better design maybe a class RegisteredUser where you can add this routine as well as other routines associated with newly registered users.

Lastly, think about underlying computer science concept. This is especially true for more complex problems. It just maybe that what you are trying to solve is a common problem with an efficient algorithm already discovered. Then again it maybe an unsolvable problem. Either way you have saved yourself a ton of time!

Putting this principle into practise will quickly deepen your knowledge and give you almost superhuman powers in solving your engineering problems. But all is not rosy in this world, it will become tempting to continue specializing to the point of losing the broader perspective of what is important in your project. At one point enough information will be just that, enough.

Do you possess deep knowledge in your field? Tell us in the comment section below.

Facebooktwittergoogle_plusredditpinterestlinkedinmail