sort descriptor optimization
sort descriptor optimization
- Subject: sort descriptor optimization
- From: "Adam R. Maxwell" <email@hidden>
- Date: Sun, 2 Jul 2006 16:53:26 -0700
Hi all,
We have an application that uses a custom NSSortDescriptor subclass
to handle nil values and empty strings differently from default.
Essentially, it looks like this:
- (NSComparisonResult)compareObject:(id)object1 toObject:(id)object2 {
NSString *keyPath = [self key];
id value1 = [object1 valueForKeyPath:keyPath];
id value2 = [object2 valueForKeyPath:keyPath];
BOOL ascending = [self ascending];
// custom sorting removed...not relevant
// header says keys may be key paths, but super doesn't work
correctly when I pass in a key path; therefore, we'll just ignore
super altogether
SEL selector = [self selector];
typedef NSComparisonResult (*comparatorIMP)(id, SEL, id);
comparatorIMP comparator = (comparatorIMP)[value1
methodForSelector:selector];
NSComparisonResult result = comparator(value1, selector, value2);
return ascending ? result : (result *= -1);
}
When sorting a large array, performance is not good; in one case, the
autorelease pool filled up and the app crashed when it ran out of
memory. The culprit in that case appeared to be valueForKeyPath:
calling substringToIndex:, so I re-implemented valueForKeyPath: to
avoid autorelease.
Further investigation with Shark, however, shows that our sort
descriptor subclass is still an order of magnitude slower than
NSSortDescriptor (with none of our custom sorting code). This is
really annoying me, and I'm wondering if anyone can point out
something dumb I've missed or indicate some possible optimizations.
It looks like -[NSSortDescriptor compareObject:toObject:] does some
caching of key paths, or somehow bypasses valueForKeyPath:
altogether, but I can't figure out how to do this.
If anyone's interested in a test app to play with Shark, I've posted
it at <http://homepage.mac.com/amaxwell> as kvcTest.zip. With our
sort descriptor subclass, I'm seeing times in the ~50 second range on
a 1.33 G4; with NSSortDescriptor, times are ~8 seconds.
thanks,
Adam
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden