When to use dispatch_once versus reallocation? (Cocoa/CocoaTouch)

Viewed 159

I often use simple non compile-time immutable objects: like an array @[@"a", @"b"] or a dictionary @{@"a": @"b"}.

I struggle between reallocating them all the time:

- (void)doSomeStuff {
    NSArray<NSString *> *fileTypes = @[@"h", @"m"];
    // use fileTypes
}

And allocating them once:

- (void)doSomeStuff {
    static NSArray<NSString *> * fileTypes;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fileTypes = @[@"h", @"m"];
    });
    // use fileTypes
}

Are there recommendations on when to use each construct? Like:

  • depending on the size of the allocated object
  • depending on the frequency of the allocation
  • depending on the device (iPhone 4 vs iMac 2016)
  • ...

How do I figure it out?

4 Answers
Related