Created
September 27, 2011 02:02
-
-
Save nolanw/1244128 to your computer and use it in GitHub Desktop.
Timing isEqual: and isEqualToString:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typical run on my machine, a late-2010 MacBook Air:
isEqualToString:
andisEqual:
are neck-and-neck when comparing strings, thoughisEqual:
always comes out ahead when comparing a string to a non-string.