Skip to content

Instantly share code, notes, and snippets.

@nolanw
Created September 27, 2011 02:02
Show Gist options
  • Save nolanw/1244128 to your computer and use it in GitHub Desktop.
Save nolanw/1244128 to your computer and use it in GitHub Desktop.
Timing isEqual: and isEqualToString:
// clang -framework Foundation isequal.m
#include <mach/mach_time.h>
#include <stdint.h>
#include <stdio.h>
#import <Foundation/Foundation.h>
// Convert from mach time to seconds (gets set in main() below).
double ticksToNanos = 0;
// Run some code many times, timing how long it took, and announce the average
// time.
#define Time(times, block) do { \
uint64_t _start = mach_absolute_time(); \
for (int _i = 0; _i < times; _i++) { \
block; \
} \
uint64_t _end = mach_absolute_time(); \
double _nanos = (_end - _start) * ticksToNanos; \
printf("%60s %.2fns mean\n", #block, _nanos / times); \
} while (0)
int main(int argc, char *argv[])
{
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
ticksToNanos = (double)timebase.numer / timebase.denom;
// Some objects to be used in timings.
NSString *interned1 = @"Ahoy there sailor!";
NSString *interned2 = @"Can you do the otter dance?";
NSMutableString *big = [[NSMutableString alloc] init];
for (int i = 0; i < 100; i++) {
[big appendString:@"I'm a pretty girl. "];
}
// Intentionally not a string, but we cast to avoid warning.
NSString *array = (NSString *)[[NSArray alloc] init];
const int times = 1e7;
Time(times, [interned1 isEqualToString:interned2]);
Time(times, [interned1 isEqual:interned2]);
Time(times, [big isEqualToString:interned1]);
Time(times, [big isEqual:interned1]);
Time(times, [interned1 isEqualToString:array]);
Time(times, [interned1 isEqual:array]);
return 0;
}
@nolanw
Copy link
Author

nolanw commented Sep 27, 2011

Typical run on my machine, a late-2010 MacBook Air:

$ clang -framework Foundation isequal.m && ./a.out 
                   [interned1 isEqualToString:interned2] 153.39ns mean
                           [interned1 isEqual:interned2] 152.31ns mean
                         [big isEqualToString:interned1] 143.30ns mean
                                 [big isEqual:interned1] 143.04ns mean
                       [interned1 isEqualToString:array] 147.17ns mean
                               [interned1 isEqual:array] 124.43ns mean

isEqualToString: and isEqual: are neck-and-neck when comparing strings, though isEqual: always comes out ahead when comparing a string to a non-string.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment