开发者

In C, would !~b ever be faster than b == 0xff?

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?


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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜