Alex Rivera | Logout

Should a developer aim for readability or performance first?

Asked 2008-10-08T14:54:32.717
105

Oftentimes a developer will be faced with a choice between two possible ways to solve a problem -- one that is idiomatic and readable, and another that is less intuitive, but may perform better. For example, in C-based languages, there are two ways to multiply a number by 2:

int SimpleMultiplyBy2(int x)
{
    return x * 2; 
}

and

int FastMultiplyBy2(int x)
{
    return x << 1;
}

The first version is simpler to pick up for both technical and non-technical readers, but the second one may perform better, since bit shifting is a simpler operation than multiplication. (For now, let's assume that the compiler's optimizer would not detect this and optimize it, though that is also a consideration).

As a developer, which would be better as an initial attempt?

Edit
Report

3 Answers

4

Putting a comment there with an explanation would make it readable and fast.

It really depends on the type of project, and how important performance is. If you're building a 3D game, then there are usually a lot of common optimizations that you'll want to throw in there along the way, and there's no reason not to (just don't get too carried away early). But if you're doing something tricky, comment it so anybody looking at it will know how and why you're being tricky.

answered 2008-10-08T15:09:38.317
1

The bitshift versus the multiplication is a trivial optimization that gains next to nothing. And, as has been pointed out, your compiler should do that for you. Other than that, the gain is neglectable anyhow as is the CPU this instruction runs on.

On the other hand, if you need to perform serious computation, you will require the right data structures. But if your problem is complex, finding out about that is part of the solution. As an illustration, consider searching for an ID number in an array of 1000000 unsorted objects. Then reconsider using a binary tree or a hash map.

But optimizations like n << C are usually neglectible and trivial to change to at any point. Making code readable is not.

answered 2008-10-08T15:24:17.977
0

IMHO both things have nothing to do. You should first go for code that works, as this is more important than performance or how well it reads. Regarding readability: your code should always be readable in any case.

However I fail to see why code can't be readable and offer good performance at the same time. In your example, the second version is as readable as the first one to me. What is less readable about it? If a programmer doesn't know that shifting left is the same as multiplying by a power of two and shifting right is the same as dividing by a power of two... well, then you have much more basic problems than general readability.

answered 2008-10-08T16:16:41.550

Your Answer