Good Code: Part Three of Five – Efficient Code

Welcome back to our five week series, where we explore five aspects of code that should really be fundamental to code being described as “good”. This week we bring you part three, after having covered Correctness in Part One and Understandability in Part Two.

Much of the series is built upon Sara Falamaki’s talk, entitled “Happy Hackers == Happy Code”, which Eric attended at Linux.conf.au 2010 in Wellington.

Feature Three: Good code should be efficient

The idea of efficient code (also termed “Algorithmic Efficiency” – you probably don’t want to click on that link; it’s incredibly detailed) is doing things in a way that is fast in that language.   For our purposes here, all you need to know is that different programming languages tend to have different methods that are faster.  For example if we needed to change the font of 10,000 cells in Excel, we would want to perform that operation on the entire group of cells, instead of looping through and performing the operation on each cell.

In this example, there are two particular things that make this code efficient.  Firstly, a single line of code…

Range(“A1:A100000”).Font.ColorIndex = 10

… is much easier to read than a (minimum) three-line loop:

For n = 1 To 100000

Cells(n, 1).Font.ColorIndex = 10

Next

But also, the speed difference between these two methods, even though they’re achieving exactly the same thing, is remarkable:  The loop took 3.170 seconds to complete, while the Range method completed in only 0.023 seconds – less than 1/100th of the time!  Even better, the Range method is easier to read, and thus is more maintainable… more on that later.

Inefficient code is most notable in large scale projects. A little extra time processing 100 cells is fine, but when you scale that up to 100000 cells, as seen in our example above, the difference really adds up. Be sure to carefully consider the efficiency of the method you are choosing, as you may save yourself precious resources in the long run.