In reference to this fine article by Matt Gallagher, I did some numerical investigations on just the test to retrieve the full set of all names of projects for a given company.
I made a loop that added 100 companies with random names at each iteration and a random number of projects, between 1 and 5, each with a random name, and did this 100 times, creating 10,000 companies w/ about 30,000 projects. Each run was done with a clean database. I timed these following test routines to grab the project names, once per company. Very quick-n-dirty. ( objc ) ✂
- (void)test1:(NSArray *)allCompanies {
for( Company *company in allCompanies )
[company valueForKeyPath:@"projects.name"];
}
- (void)test2:(NSArray *)allCompanies {
for( Company *company in allCompanies )
[company.projects valueForKey:@"name"];
}
- (void)test3:(NSArray *)allCompanies {
for( Company *company in allCompanies ) {
NSMutableSet *result = [NSMutableSet set];
for (Project *project in company.projects) {
NSString *value = project.name;
if (value)
[result addObject:value];
}
}
}
- (void)test4:(NSArray *)allCompanies {
for( Company *company in allCompanies ) {
NSSet *projects = company.projects;
NSMutableSet *result = [NSMutableSet setWithCapacity:[projects count]];
for (Project *project in projects) {
NSString *value = project.name;
if (value)
[result addObject:value];
}
}
}
- (void)test5:(NSArray *)allCompanies {
for( Company *company in allCompanies )
[company.projects objectValuesForProperty:@selector(name)];
}
Test 5 uses Matt's -objectValuesForProperty: category on NSSets.
I saved the outputs to textfiles and plotted them (using matplotlib) to produce this:
Key:
test1 = green
test2 = blue
test3, test4, test5 = the other colors that are basically all the same line
If you read Matt's article, you'll note that I didn't see the differences that Matt was able to tease out between tests 3 and 4, but I'm sure it's a function of our different, um, functions. Not sure why. Perhaps this test is just too simple or small.
I was impressed at how much faster the test ran in test2, just swapping out the line [company valueForKeyPath:@"projects.name"] for [company.projects valueForKey:@"name"].
My test probably has all kinds of problems with it that don't show off the advantages well enough, and I probably should have written something that looks up, say, employee names, and maybe that's the next test I'll make. This is interesting enough for now to post.