0

I use performSelector:withObject:afterDelay: to delay a layout operation so that it's not done multiple times. Normally, I do something like this (example only):

- (void) setViewNeedsLayout{
    if (!_viewsNeedLayout){
        _viewsNeedLayout = YES;
        [self performSelector:@selector(layoutViews) withObject:nil afterDelay:0];
    }
}

- (void) layoutViews{
    _viewsNeedLayout = NO;
    //layout views
}

It's pretty simple, efficient and effectively delays the layout operation until the end of the current run loop, but it does require that I keep track of the ivar: _viewsNeedLayout.

However, I'm wondering about the performance of cancelPreviousPerformRequestsWithTarget:selector:object:. Instead of using an iVar to keep track of whether I've kicked off the delayed selector, I'm wondering if it might be better to do something like this:

- (void) setViewNeedsLayout{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(layoutViews) object:nil];
    [self performSelector:@selector(layoutViews) withObject:nil afterDelay:0];
}

Now, the issue is how performant is cancelPreviousPerformRequestsWithTarget? In some cases, the respective setViewNeedsLayout method (or equivalent) could get called possibly hundreds of times... as an extreme example. But it is an easier way to deal with the delayed/queued method call so I'd prefer to use it if it's not going to have a significant impact on performance.

Aaron Hayman
  • 8,492
  • 2
  • 36
  • 63
  • It shouldn't affect performance. But it should also be easy for you to test. – Wain Nov 12 '13 at 15:33
  • No, it shouldn't be hard to test but if someone already has already done the testing then I figured it would be good to have it up on SO. If not, then I'll do the testing and post it as the answer in a week or so. – Aaron Hayman Nov 12 '13 at 15:43

0 Answers0