开发者

What's the fastest way to switch between a zero and non-zero integer value in Objective-C?

I have an integer "myInt" in some Objective-C code. myInt is used as a boolean... hence I'm only interested in zero or non-zero values. I'd like to quickly switch between zero and a non-zero value. What's the fastest way to do this?

Here's what I've tried so far: (All of these work)

Try 1:

开发者_开发技巧
// myInt is initialized to 0
if(myInt == 0){
    myInt = 1;
}else{
    myInt = 0;
}

Try 2:

myInt = !myInt;

Try 3:

myInt ^= 0xffffffff;

I realize I could just measure the performance with a profiler... however I decided to ask on SO because I hope that others (any myself) can learn something from the discussion motivated by this question.


Try 2 is the most compact, cleanest, and easier to maintain. Why second guess the compiler's optimization?


In general, to switch between 0 and some constant integer a, use

myInt = a - myInt


It depends. Are you compiling for ARM, x86_64, i386, PPC, or 6502?

The difference is academic, but if you really want to know which is faster you will have to look at the disassembled code generated by your compiler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜