0

RE: Objective-C - When to use 'self'

I understand when SELF is actually required 100% to properly set a retained property but is there any overhead to continually calling the getter method, instead of accessing directly even after you've already obtained your retained object? Is the program more efficient not continuously calling it?

Your ViewController contains many retained subviews (ie. multiple retained UIViews) which get added to the root main view.

Inside your viewDidLoad: method is there any overhead doing:

[self.mySubViewA setBackgroundColor:[UIColor blueColor]];
[self.mySubViewA setOpaque:NO];
[self.mySubViewA setAlpha:1.0f];

[self.view addSubView:self.mySubViewA];

[self.mySubViewB setMyCustomPropertyInThisView:[UIColor redColor]];
....

instead of:

// no calls to SELF at all (i.e saving time on method get cycle calls and directly
// accessing the properties currently retained at that address.
// Assumption here is that mySubViewA is loaded through NIB and is already alloc'd.
[mySubViewA setBackgroundColor:[UIColor blueColor]];
[mySubViewA setOpaque:NO];
[mySubViewA setAlpha:1.0f];

// Is this faster? since we just instantly assign the UIView @ mySubViewA to the main view
// as opposed to a method get cycle?
[self.view addSubView:mySubViewA];

[mySubViewB setMyCustomPropertyInThisView:[UIColor redColor]];
....
Community
  • 1
  • 1
skålfyfan
  • 4,931
  • 5
  • 41
  • 59

2 Answers2

1

Yes, of course there is an overhead. Using self.… means another method call which takes more time than a simple assignment. How much more, depends on how the getter is implemented (e.g. if the property is nonatomic or not).

More importantly, unless you can identify this additional overhead to be a bottleneck in your specific case, you should not care about it. Using the getter has many advantages and you should not prematurely forgo them just to improve performance where it isn't necessary.

Ole Begemann
  • 135,006
  • 31
  • 278
  • 256
0
[ self.foo bar ];

is equivalent to 2 method calls:

temp = [ self foo_Getter ];    // first method call
[ temp bar ];                  // second method call

so, of course, there will be more Objective C runtime method dispatch overhead.

However you might only ever find this overhead measurable inside the inner loops of some compute bound routine (numeric, audio, image processing, etc.). So outside inner loops, write readable maintainable code. Inside inner loops, use temporary local variables as necessary to avoid any repeated method dispatches that the compiler can't optimize away (except when that violates memory management rules, etc.)

hotpaw2
  • 70,107
  • 14
  • 90
  • 153