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

Handling tough decisions

First day on the job you probably, arbitrarily chose your first language or even more likely someone else chose it for you. Your path has so far been easy with what you need to do either being dictated to you by some kind of boss figure. This maybe literally your boss, a client or even market forces.

However as your career grows, you will find yourself having to make more and more decisions. Your decisions will have far reaching impact and will likely be affecting not only your but other individuals as well. As you grow into this new roles you might need some new tools in your tool set to help you deal with some tough decisions.

What makes a decision tough? The obvious answer would be a decision that has a huge impact. If you thought so, then you would be wrong. To demonstrate this, think, if you came across a person shot and wounded in the street, would the decision to take them to hospital be a tough one? Yet the impact would be huge!

So what does make a tough decision? You have yourself a tough decision when among the options there are no clear winners, one option is good in this way the other option is good in the other way.

Finding yourself in this position can be agonizing where at night you sleep having decided to go with option A and wake up feeling option B might have been a better option after all.

While there are no silver bullets, there certainly are strategies of dealing with such issues, one of which I am going to present today.

Weighted Average Decision Matrix (WADM)

WADM is decision tool that helps you break down the decision into decision factors which you can then quantify and compute to come up with an objective value of a better decision.

To work, the tool requires at least two decisions. In our case we are going to give an example of PHP frameworks.

Your team has been tasked with building a cutting edge SAAS application and you need to choose between using Phalcon with its super performance or Laravel with its expressive style. Which one will you go with?

Step 1: List out the factors

List out all the factors that are important in a framework when building your SAAS.

Step 2: Write relevant importance

On a scale of 1 – 10 write out how important each factor is in your decision

Step 3: Weight the options

For each option rate it on 1-10 on how the option fairs in that factor.

Step 4: Calculate Weighted options

For each factor multiply the relevant importance by the weight of the option. I have separated out the weight for easier computation in a spreadsheet.

Step 5: Compute the sum

Finally compute the sum of the weighted options to get your decision.

Using the WADM method, we have been able to establish that Laravel is the better option for your project.

Hopefully this technique will save you countless hours agonizing over your decisions.

How do you handle tough decisions? Tell us in the comment section below.

You can check out the spreadsheet used here.

https://docs.google.com/spreadsheets/d/1213-Vclsm7jE2hO346rwdtzKoUSmp7VWDU6y07_F9IY/edit?usp=sharing

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