Efficient code – a quiz
I was recently reading a set of “golden rules” for embedded programming. I am very skeptical about such proscriptive instructions as, for them to be valid, a great many assumptions must be made and clearly stated. These rules were supposed to promote the production of safe, efficient code. I am OK with “safe” – that simply means that the code does what it is supposed to do, without deviation as a result of unexpected data or unexpected side-effects. I am not so sure about “efficient”, as that depends entirely on the design parameters in force; it might mean fast or it might mean small, for example. And what about maintainability and portability being significant parameters?
So, instead of trying to outline rules myself, I thought that I might set out to find out what real developers think …
Just for fun [budgets to not stretch to offering a prize], I would like to pose a question and request answers by comment or email:
You are developing a system, where execution speed is important. At one point in the code, there is an unsigned integer variable x which needs to be divided by 8. I can immediately think of 4 ways to code this:
x /= 8;
x = x / 8;
x >>= 3;
x = x >> 3;
My question is: which of these options is the most efficient and why? Of course, if you have other suggestions about how to address the problem, I would be very interested to hear.
I will publish some results and my answer in a couple of weeks.