Tag Archives: readability

Readability vs Performance

A question that pops up often on StackOverflow is: which method is better x or y?

For example, which is better?

lazy-or

if ($a === "foo" || $a === "bar" || $a === "baz") {
    do_something();
} else {
    do_something_else();
}

in_array

if (in_array($a, array("foo", "bar", "baz")) {
    do_something();
} else {
    do_something_else();
}

There are several ways to approach this. A clever programmer might say: Faster is better right? Let’s benchmark! So he writes a script to accurately time the difference.
That’s not so easy as it may seem. The performance characteristics vary case-by-case.
What if you have not 3 but 10 values? What if you have 100? What if the first case is the most likely case and the other 2 only rarely get hit?

Let’s take a step back. In this example, does it really matter which method is faster? I would argue: no. Imagine your program has a bottleneck in it, you’re tasked with finding it and resolving it. If you saw either of these code samples, would you bother trying to see if the bottleneck is here? No, of course not. If you saw this code and you had to add a value would you take the time to convert one form to the other? Probably not (I wouldn’t).

That is why in almost all cases performance doesn’t matter. If your input is really really small (< 10) don't bother with optimization.
What you should bother with is readability. Which of these methods is more readable? I would say, in this case, it doesn’t really matter. If the list gets a bit bigger to 4 or 5 values then maybe the in_array one is preferred because it will fit on one line. If your list of allowed values is a dynamic list, because of a clever algorithm, then sure, go for the in_array variant. If you see the lazy-or variant and you need to add a 4th case, I wouldn’t object if you added another || case.

Most of the arguments I use are arguments that come from experience. Seeing a lot of code, seeing code that works and code that doesn’t. The most common way to get a bug is to write code that is easy to misunderstand or misuse. And even as a novice programmer you know this. What you don’t know is whether the code you’re currently writing is well readable or not. You haven’t yet learnt the warning signs of smelly code. A general rule of thumb: simpler is better. Simpler code is easier to write, easier to read, easier to debug, faster to write and it probably performs really well.