James's Twisted Ape

Thoughts, code and anything else.

The Best Code Isn't Always the Most Readable

I often see it expressed that the best solution to a problem is the most readable to other people. I do not agree with this, it is often enough to know what the code does, not how it does it. For example a good function to count the number of bits in an integer is:

  int countSetBits (uint64_t a) {
    Counts the number of set Bits
    Uses Hamming weight https://en.wikipedia.org/wiki/Hamming_weight.
  a = a - ((a >> 1) & 0x5555555555555555);
  a = (a & 0x3333333333333333) + ((a >> 2) & 0x3333333333333333);
  a = (a + (a >> 4)) & 0x0f0f0f0f0f0f0f0f;
  return (a * 0x0101010101010101) >> 56;

This code isn’t immediately understandable; it doesn’t matter as it has a good name and a comment directing people where to find out how it works (if they’re interested).

Code isn’t intrinsically better because everyone can read it and immediately understand it. Almost all of the code that we run is entirely inside the blackbox of a method/function. It’s enough that somebody else has understood it and checked that it works. The above code can be easily checked against the trival algorithm for all values.

Whilst there isn’t anything wrong with writing complex code (code that can’t be understood immediately, without additional reading/thought), there’s also no reason to go out of our way looking for the fastest way. In this case it would be incredibly easy to write a loop to count the number of set bits. If you don’t already know about the above algorithm then you may as well get on with your job and write the simple algorithm. If profiling your code at the end shows that this section needs to go faster, look up a faster way to write the code.