tags:

views:

33

answers:

3

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.

+4  A: 

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

David Sowsy
+2  A: 

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

myInt = a - myInt
ergosys
+2  A: 

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.

Darren
ARM if that helps
MrDatabase