Question

I use == and != a lot in my code and I was wondering which is quicker in objective c so that I can make my app as fast as possible.

Situation

I have a variable which is one of two things and I want the quickest method to see which one it is

Thanks in advance

Était-ce utile?

La solution

You should not worry about this level of detail for performance reasons, unless you've identified a performance issue.

However, wondering to satisfy an inquiring mind is a different matter! :-) The answer is they are identical.

A comparison is usually compiled as an instruction which sets condition flags; this could be a specific comparison instruction or something like an arithmetic instruction which sets condition codes; followed by a conditional jump which tests the condition flags - and a test for "equal" is the same cost as for "not equal", just a different setting of those condition flags.

This also means that statements such as if([some method call]) ... and if(![some method call]) ... have the same cost - the "not" operator produces no extra code.

Autres conseils

You can test yourself. Check current milliseconds before and after operating. I guess there's no differences..

If you really need to know, you could make a lot of operating with loop.

then you will get the answer.

This is silly. You would have to execute millions of iterations of code using the 2 versions of if statement in order to even detect a difference in speed. This is a triviality, and not worth worrying about.

As the other poster said, == and != should take exactly the same amount of time for non-floatingpoint values. For floating point, there might be some differences, since for an equal comparison the processor has to first normalize the 2 floating point values, then compare them, and normalizing is relatively time-consuming. I don't know if testing for non-equality if slower than equality. IT's unlikely but not impossible.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top