Writing Code for Better Performance

Categories Articles

Writing code is mostly science, but it’s also partly an art form.  In fact learning to program is quite similar to learning to be a ninja.  It’s all about being silent and fast.  Or at least that’s how your programs should be.  When you’re coding for the web, it’s even more important to get that ninja-like finesse.  Your programs need to eke out as much speed as possible, and be without error, so that they don’t make noise.  The main thing a good program has in common with a ninja is flawless execution.

Imagine a ninja stealthily creeping up on his enemy.  At one with the shadows, he gracefully draws his ninjato blade in one smooth motion.  Just as he is about to strike, a massive gong rings out directly behind him, startling him out of his wits.  The frustration he feels as the enemy runs away to safety is exactly the same (probably) frustration website users feel when they encounter the dreaded JavaScript Error alert box.

You need to make your code efficient so it runs smoothly and doesn’t create an unfavorable impression.  It’s way more important than you may think.  Small coding errors can lead to really big problems in exceptional situations.

The major challenge of programming for the web is that you don’t know exactly the operating environment or capabilities of the user’s system.  Any other kind of software can be purpose-built for specific operating environments with known capabilities.  This makes web programming somewhat unique, and—contrary to what many people think—demands a high level of skill from the programmer.

One important thing to keep in mind is that most optimizations will normally result in very small improvements that will only be really significant if huge amounts of processing is taking place.  The size of your application in bytes is also a really important consideration compared to programming for ordinary desktop scenarios because a JavaScript or PHP program must load entirely into memory before it performs any tasks.  Thus the more instructions your program includes, the more inefficient it will be.  Further inefficiency will be introduced if various components of the program are not stored locally.  In the worst cases, individual components of a program may fail to download, which can cause the program to either fail or to work in unintended ways.

1. Program in a popular language so you don’t bottleneck yourself

There are all kinds of programming languages you could choose.  PERL, Python, Ruby, PHP.  Anyone still remember ColdFusion?  You could throw that in the mix too.  And let’s not forget JavaScript or even VBS.  Alright, you can forget VBS if you want.

All of these different languages have their pros and cons, but one thing to keep in mind is that JavaScript and PHP are currently the most popular and for a good reason.  These languages are easy to learn, and if you know one, you can more easily learn the other.  It doesn’t require the same huge shift in methodology to go from JS programming to PHP programming, compared with making the jump to programming in Ruby or Python.

If you’re programming in one of the less popular languages like PERL, you will have difficulties getting help with problems you encounter along the way, because there are fewer PERL programmers that you can turn to for help, and fewer resources available to help you.

None of this, you will notice, has anything to do with the efficiency of your program, but it does have an impact on your efficiency.  If you program in a complicated language that is difficult to read and which is unpopular, you’ll be slower than somebody writing a similar program in a more popular language.

2. There’s more than one way to do almost anything

Programming is all about problem solving.  That’s partly procedural, but it’s also a creative task as well.  You are essentially designing solutions to problems.  As with any creative solution, there are multiple ways to achieve the goal.  Your mission, should you choose to accept it, is to come up with the best solution.

What you may not have realized is that where programming languages offer many ways to achieve something, not all of these ways are equal.  In a situation where your program is fully compiled before execution, it’s less of a big deal, because an intelligent compiler can convert code to its most efficient form.  Interpreted execution environments like Java, JavaScript, PHP, etc, don’t give you that luxury.  They are not compiled by a compiler attempting to make them as efficient as possible, but by an interpreter which accepts your instructions as they are written.

Thus if there are two ways to do something (PHP’s echo and print commands, for example) where one is more efficient than the other, no conversion takes place.  Although in practice it makes very little difference, echo is marginally more efficient than print because it doesn’t generate a return value.  The difference is so small that it wouldn’t be noticed in even the largest program you could possibly write.  Echo offers an advantage of being able to accept multiple values in CSV form, whereas print can’t do that.  Echo is also more widely used, and more conventional than print, which is a good enough reason to prefer it.  The important takeaway point is that the interpreter won’t magically convert your print statements to echo statements just because they are more efficient, but some compilers would do that.

It gets more interesting when we come to conditional execution and iteration.  Remember what was stated earlier about the total number of individual instructions having a bearing on performance, and it is in your interest to reduce the number of instructions as much as you can.

If we look at a typical for loop and compare it to a typical while loop, we can easily see which of them will be more efficient in JavaScript or PHP (but not necessarily in another language like C++).  For readability, we’ll use PHP for the example.



echo $i;



Compare with:


echo $i;


By using a for loop instead of a while loop, we got to eliminate two whole instructions.  More importantly, though, the variables used in the for loop are declared as part of it and not separately, which makes it less easy to accidentally create an eternal loop.  If you forget to add the increment instruction before the closing brace in the while loop, it will never stop looping.  It’s nearly impossible to do this with a for loop.

The for loop is easier to read and understand, which improves the maintainability of the code, and makes debugging easier.  It is also a little safer due to compartmentalizing the iteration variable, so it can’t be confused with other parts of your code.

You will see while loops more frequently used when it comes to fetching SQL data.  If the data returned is very large, the while loop will actually execute faster because it needs fewer instructions to achieve the same results and uses less variables.  It is the complete inverse of the normal situation.

When it comes to choosing between switch and if/else, you have to make a choice between the marginally faster execution provided by a switch statement and the much easier maintainability of if/else.  Just in case you are interested, the interpreter produces machine code that is 80% smaller in size when you use a switch statement, but the actual performance hit is only one tenth of a second.

3. Try everything once

If your programming language supports error handling like try/catch/throw, then use those methods to circumvent problematic results.  It is better for your program to apply the brakes and halt itself rather than simply crashing.

4. Strip out anything that’s not needed

This especially applies to JavaScript, where it’s quite common for programmers to include many third-party scripts as part of their solution.  Most programmers don’t take the time to edit out unused parts of those scripts, so the result is wasteful bloat.

Bloating also occurs during the programming process.  Often we include all kinds of little testing snippets that have no real bearing on the task at hand (writing output to the console, for example), and it’s important to remember to remove all that junk prior to actually uploading the code.

5. Use single quotes in PHP where you can

It’s tempting to make use of PHP’s ability to parse variables inside double quotes, but it is terribly inefficient.  Using single quotes and concatenation is faster.  For example:

echo “Hello $name”;

Is slower than:

echo ‘Hello ‘ . $name;

It’s not going to be noticeable if that’s the only instance, but it will be noticeable if you have many instances of double quotes in a program.  This isn’t an issue in JavaScript because JS doesn’t parse double quoted strings.

Efficiency is achievable

It may sound like it’s really complicated to make programs efficient, but actually it’s very easy as long as you always choose the path of least resistance.  Which is also what you get taught on the first day of ninja training. Study what works best and use that in preference to other ways unless you have a good reason to do it differently.  If you can shave 4 or 5 seconds off a 30 second load time, it might make all the difference to avoiding unnecessary bounces, and from a web programming point-of-view, that is worth aiming for.

header image courtesy of ranganath krishnamani

Emma Grant is a professional freelance content writer from Ireland. Over the past three years she has travelled the world while running her business from her laptop. You find her at www.florencewritinggale.com