Reputation: 64478
Consider this Objective-C code (ARC enabled):
[self.aProperty sendMessage];
if (self.aProperty)
{
[self doSomethingWithProperty:self.aProperty];
}
I'm wondering if rewriting the code to the snipped below would be any faster (in release builds):
MyPropertyClass* myProperty = self.aProperty;
[myProperty sendMessage];
if (myProperty)
{
[self doSomethingWithProperty:myProperty];
}
The question being if the Apple LLVM Compiler 3.0 is able to optimize repeated access to property getters? Does it make any difference if the property is nonatomic?
If I had to guess, I would say writing the code below is faster, because the compiler has no guarantee that self.aProperty doesn't change during these lines. Am I right?
Upvotes: 4
Views: 388
Reputation: 237010
More important than the question of atomic vs. nonatomic is that getters aren't guaranteed to be pure or idempotent. Calling a getter multiple times may not be equivalent to calling it once. For example, someNSEnumerator.nextObject
will return a different result every time you call it. So such an optimization is not possible in the general case.
However, with regards to "faster," I doubt either code snippet will be appreciably faster. The correct answer is to profile and see if it makes any difference if this code is running often enough to be worth the trouble.
Upvotes: 7