Created
September 4, 2008 12:12
-
-
Save mootoh/8760 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /* | |
| * compare [NSObject alloc] with malloc(sizeof(NSObject)) | |
| * | |
| * build: | |
| * cc -Wall -g -framework Foundation alloc_cost.m | |
| * | |
| * result: | |
| * % ./a.out | |
| * sizeof(NSObject)=4 | |
| * elapsed time of [NSObject alloc] = 0.235727 | |
| * elapsed time of malloc(sizeof(NSObject)) = 0.073298 | |
| * on MacBook C2D. | |
| * | |
| * => malloc seems to be 3 times faster, | |
| though NSObject would be very sophisticated and | |
| sizeof(NSObject) may not be the correct metrix. | |
| * | |
| */ | |
| #include <stdio.h> | |
| #include <sys/time.h> | |
| #import <Foundation/Foundation.h> | |
| #define LOOP_COUNT (1024 * 1024) | |
| #define START_TIMER gettimeofday(&start, NULL); | |
| #define STOP_TIMER gettimeofday(&stop, NULL); | |
| long elapsed(struct timeval *start, struct timeval *stop) { | |
| return (stop->tv_sec * 1000000 + stop->tv_usec) - | |
| (start->tv_sec * 1000000 + start->tv_usec); | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
| int i; | |
| struct timeval start, stop; | |
| printf("sizeof(NSObject)=%ld\n", sizeof(NSObject)); | |
| START_TIMER; | |
| for (i=0; i<LOOP_COUNT; i++) { | |
| NSObject *obj = [NSObject alloc]; | |
| } | |
| STOP_TIMER; | |
| printf("elapsed time of [NSObject alloc] = %f\n", (float)elapsed(&start, &stop) / LOOP_COUNT); | |
| START_TIMER; | |
| for (i=0; i<LOOP_COUNT; i++) { | |
| void *obj = malloc(sizeof(NSObject)); | |
| } | |
| STOP_TIMER; | |
| printf("elapsed time of malloc(sizeof(NSObject)) = %f\n", (float)elapsed(&start, &stop) / LOOP_COUNT); | |
| [pool release]; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment