Skip to content

Instantly share code, notes, and snippets.

@torsten
Created March 27, 2012 08:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torsten/2214008 to your computer and use it in GitHub Desktop.
Save torsten/2214008 to your computer and use it in GitHub Desktop.
Benchmark to measure how much slower property access is vs direct member access.
// Compile as: clang -O4 -framework Foundation property-access.m && ./a.out
#import <Foundation/Foundation.h>
// Performance timer, credit: Lars Schneider @kit3bus
#import <mach/mach_time.h>
#define MAKE_NSSTRING(str) (NSString *)CFSTR(#str)
#define START(name) \
uint64_t name##_startTime = 0;\
uint64_t name##_endTime = 0;\
uint64_t name##_elapsedTime = 0;\
uint64_t name##_elapsedTimeNano = 0;\
mach_timebase_info_data_t name##_timeBaseInfo;\
mach_timebase_info(&name##_timeBaseInfo);\
name##_startTime = mach_absolute_time();\
#define STOP(name) \
name##_endTime = mach_absolute_time();\
name##_elapsedTime = name##_endTime - name##_startTime;\
name##_elapsedTimeNano = name##_elapsedTime * name##_timeBaseInfo.numer / name##_timeBaseInfo.denom;\
NSLog(@"Time %@ %"PRIu64"ms", MAKE_NSSTRING(name), name##_elapsedTimeNano / 1000000);\
@interface MyObject : NSObject
{
@public
NSString * _string;
}
@property (retain) NSString *string;
@end
@implementation MyObject
@synthesize string = _string;
@end
int main (int argc, char const *argv[])
{
size_t times = 1000000;
MyObject * obj = [[MyObject alloc] init];
START(property_access);
for(size_t i = 0; i < times; ++i)
//[obj setString:@"FOO bar"];
obj.string = @"FOO bar";
STOP(property_access);
START(ivar_access);
for(size_t i = 0; i < times; ++i)
obj->_string = @"FOO bar";
STOP(ivar_access);
[obj release];
return 0;
}
Time property_access 8ms
Time ivar_access 0ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment