advantis
5/15/2013 - 10:37 AM

Comparator benchmark

Comparator benchmark

/* All measurements were done on iPhone 4 */
 
// MRC:
// descriptor sorting time: 18.503416ms
// comparator sorting time: 4.665041ms
// concurrent comparator sorting time: 4.703520ms
 
// ARC (w/o __unsafe_unretained):
// descriptor sorting time: 19.011437ms
// comparator sorting time: 14.852541ms
// concurrent comparator sorting time: 14.606791ms
 
// ARC (w/ __unsafe_unretained):
// descriptor sorting time: 19.062041ms
// comparator sorting time: 5.439478ms
// concurrent comparator sorting time: 5.114479ms

@interface ScalarContainer : NSObject
@property (nonatomic) double doubleValue;
@end

@implementation ScalarContainer
@end

- (void) performTest
{
    const NSUInteger ObjectCount = 1000;
    const NSUInteger TestCount = 100;

    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:ObjectCount];
    for (NSUInteger i = 0; i < ObjectCount; ++i)
    {
        ScalarContainer *container = [ScalarContainer new];
        container.doubleValue = (double) arc4random() / (double) arc4random();
        [array addObject:container];
    }

    NSComparator comparator = ^(/*__unsafe_unretained*/ ScalarContainer *container1, /*__unsafe_unretained*/ ScalarContainer *container2) {
        double value1 = container1.doubleValue;
        double value2 = container2.doubleValue;
        return value1 < value2
                ? NSOrderedAscending
                : value2 < value1
                    ? NSOrderedDescending
                    : NSOrderedSame;
    };

    NSLog(@"descriptor sorting time: %fms", (1. / NSEC_PER_MSEC) * ADVGetMedianExecutionTime(TestCount, ^{
        NSMutableArray *array1 = [array mutableCopy];
        NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"doubleValue" ascending:YES];
        [array1 sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
    }));

    NSLog(@"comparator sorting time: %fms", (1. / NSEC_PER_MSEC) * ADVGetMedianExecutionTime(TestCount, ^{
        NSMutableArray *array2 = [array mutableCopy];
        [array2 sortUsingComparator:comparator];
    }));

    NSLog(@"concurrent comparator sorting time: %fms", (1. / NSEC_PER_MSEC) * ADVGetMedianExecutionTime(TestCount, ^{
        NSMutableArray *array3 = [array mutableCopy];
        [array3 sortWithOptions:NSSortConcurrent usingComparator:comparator];
    }));
}