Does anyone know what’s the performance difference between using valueForKeyPath with collection operator vs looping the collection one-by-one and manually does the calculation? For example:
NSSet* myObjects = [NSSet setWithObjects:obj1, obj2, obj3, nil];
NSNumber* sum = [myObjects valueForKeyPath:@"@sum.myProperty"];
vs
NSSet* myObjects = [NSSet setWithObjects:obj1, obj2, obj3, nil];
int sum = 0;
for(MyObject* obj in myObjects)
sum += obj.myProperty.intValue;
Any thoughts?
I believe your question is based on a misunderstanding of the common use of collection operators. The common use is for Core Data, where the data can be accumulated more efficiently in SQL without having to fault the entire object.
In my experience, simple loops are much faster for in-memory
NSSetorNSArraybacking stores.