开发者

C syntax or binary optimized syntax?

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 t开发者_开发技巧he traditional C syntax or better to find a binary optimized one if possible?


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.


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


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜