tags:

views:

120

answers:

4

Let's take a simple example of two lines supposedly doing the same thing:

if (value >= 128 || value < 0) ...

or

if (value & ~ 127) ...

Say 'If's are costly in a loop of thousands of iterations, is it better to keep with the traditional C syntax or better to find a binary optimized one if possible?

+4  A: 

I would use first statement with traditional syntax as it is more readable. It's possible to break the eyes with the second statement.

Care about programmers who will use the code after you.

Bar
+4  A: 

In 99 cases out of 100, do the one which is more readable and expresses your intent better.

Simon Nickerson
+1  A: 

In theory, compilers will do this sort of optimization for you. In practice, they might not. This particular example is a little bit subtle, because the two are not equivalent, unless you make some assumptions about value and on whether or not signed arithmetic is 2's complement on your target platform.

Use whichever you find more readable. If and when you have evidence that the performance of this particular test is critical, use whatever gives you the best performance. Personally, I would probably write:

if ((unsigned int)value >= 96U)

because that's more intuitive to me, and more likely to get handled well by most compilers I've worked with.

Stephen Canon
You are right about the practice part, they usually do not over-optimized that much, even in -o3, that is why I asked the question. With thousands of iterations the difference can be huge.I don't see the point of the unsigned in that example though?
Dpp
@Dpp: If `value` is an `int`, then any negative value will become larger than 96 when it is converted to `unsigned int`, so this removes the need for a separate test for < 0.
caf
Ho yeah, because of the 8th bit set to 1, I like it! And then the pre-compiler might optimize it better!
Dpp
@Dpp: What caf said; more precisely, I'd do it this way because (a) it's guaranteed by the C standard, instead of depending on signed arithmetic being 2s complement, and (b) cmp-branch is heavily optimized for in processor design, and can be faster than and-branch or and-test-branch on some platforms.
Stephen Canon
+1  A: 

It depends on how/where check is. If the check is being done once during program start up to check the command line parameter, then the performance issue is completely moot and you should use whatever is more natural.

On the other hand, if the check was inside some inner loop that is happening millions of times a second, then it may matter. But don't assume one will be better; you should create both versions and time them to see if there is any measurable difference between the two.

R Samuel Klatchko