1
@interface Person : NSObject
@property(nonatomic, assign) CGFloat salary;
@end

@implementation Person
- (void)addSalary:(CGFloat)s
{
    _salary += s; **//method 1**
    self.salary += s; **//method 2**
}
@end

I wonder which is more efficient between method 1 and 2? Would the compiler do some optimisation work to make them have the same performance?

qiyu
  • 71
  • 6
  • Read all the points here : http://stackoverflow.com/questions/4142177/difference-between-self-ivar-and-ivar?rq=1 – Lithu T.V May 06 '13 at 10:57
  • That question is not about the performance between self.ivar and ivar. Somebody advise to use self.ivar, it makes sense in non ARC environment. If ARC adopted, no memory leak will be brought in with ivar even if it is an id instance. So I want to know whether the performance is the same or not? "Accessors are highly optimized in Objective-C and provide important features for maintainability and flexibility. As a general rule, you should refer to all properties, even your own, using their accessors." from <> . – qiyu May 07 '13 at 04:27

2 Answers2

3

Obviously, using _salary will be faster than self.salary and I doubt that the compiler can do (in the general case) any optimization here either simply because there is no guarantee that a subclass would not implement -salary or setSalary: itself. Then there is all the aspects of key-value notifications. Setting self.salary will trigger key value observers while using the ivar wont. My take is that unless you are in a very large and tight loop, it won't make a noticable difference in your app and using self.salary is more robust in that it allows for the possibility of subclasses. I could also add that the objective-c runtime is very efficient in it's dispatch of methods.

aLevelOfIndirection
  • 3,522
  • 14
  • 18
0

Method 1 will be as fast or faster than method 2. But you should still use method 2 for other reasons. See https://stackoverflow.com/a/16012387/1597531

Community
  • 1
  • 1
Markus
  • 528
  • 1
  • 5
  • 10