views:

230

answers:

4

From a long time ago I have a memory which has stuck with me that says comparisons against zero are faster than any other value (ahem Z80).

In some C code I'm writing I want to skip values which have all their bits set. Currently the type of these values is char but may change. I have two different alternatives to perform the test:

if (!~b)
    /* skip */

and

if (b == 0xff)
    /* skip */

Apart from the latter making the assumption that b is an 8bit char whereas the former does not, would the former ever be faster due to the old compare to zero optimization trick, or are the CPUs of today way beyond this kind of thing?

+10  A: 

If it is faster, the compiler will substitute it for you.

In general, you can't write C better than the compiler can optimize it. And it is architecture specific anyway.

In short, don't worry about it unless that sub-micro-nano-second is ultra important

Aiden Bell
Well I'm pretty sure that even if it was faster, the rest of the code would reduce the speed increase to zero. I do know to not worry about micro-optimizations, but just can't help myself sometimes ;-)
James Morris
+3  A: 

I would say it's not so much the that CPUs are beyond these kind of tricks as it is the compilers.

The CPUs of today are, however, beyond simple tricks which pull an extra clock-tick or two of speed. Even if you do this 100,000 times a second, we are still only talking about an increase in speed of 0.00003 seconds on a single-core 3Ghz computer - it is simply not worth your time to worry about things like this.

BlueRaja - Danny Pflughoeft
+7  A: 

From what I recall in my architecture classes, I believe they should be equally fast. Both have 2 instructions.

First example 1. Negate b into a temp register 2. Compare temp register equal 0

Second example 1. Subtract 0xff from b into a temp register 2. Compare temp register equal to 0

These are basically identical, and besides, even if your particular architecture requires more or less than this, is it really worth the fraction of a nanosecond? Several minutes have been spent just answering this question.

Tesserex
+1 for -- "Several minutes have been spent just answering this question."
Aiden Bell
+2  A: 

Go with the one that will be easier for the person who is maintaining your code to understand. If you have a successful product, most of the expense in software is in maintenance. If you write cryptic code you add to that expense. If you don't have a successful product, it doesn't matter because no one will have to maintain it. I have been in situations where I had to save every byte I could, and had to resort to tricks like the one you gave, but I only do it as the very very very last resort.

Jim Tshr