Last active
August 29, 2015 14:06
-
-
Save nicklockwood/e940105c6c0a62b6a0b7 to your computer and use it in GitHub Desktop.
Mutable collection worst case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//here is an array factory method | |
@interface Foo: NSObject | |
@end | |
@implementation Foo | |
+ (NSArray *)newArray | |
{ | |
NSMutableArray *array = [NSMutableArray array] | |
[array addObject:@"Hello"]; | |
[array addObject:@"World"]; | |
return array; //don't both copying, to improve peformance | |
} | |
@end | |
//here is a class that accepts an array, and uses copy semantics (according to best practice) | |
@interface Bar: NSObject | |
@property (nonatomic, copy) NSArray *array; | |
@end | |
@implementation Bar | |
@end | |
//here is where I use it | |
NSArray *foo = [Foo newArray]; | |
NSMutableArray *bars = [NSMutableArray array]; | |
for (int i = 0; i < 10000; i++) { | |
BarClass *bar = [Bar new]; | |
bar.array = foo; | |
[bars addObject:bar]; | |
} | |
//problem: I'm assuming this will be efficient because I'm adding the same instance of foo to each new Bar. | |
//but unfortunately, because foo is secretly mutable, I'm actually copying it each time around the loop | |
//if +newArray had returned an immutable array by copying internally, I'd avoid 9999 additional copies |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment