Which is more memory efficient and faster , Instance method or class method in Objective-C?
我知道何时使用类方法以及何时使用实例方法(当需要对对象的特定实例进行操作的代码时,应该创建实例方法)。当需要做一些通常涉及该类但可能不在该类的任何特定对象上操作的事情时,可以创建一个类方法。但是如果我有这两个选项,如何决定是使用类方法还是实例方法呢?选择一种方法的因素(效率、速度等)是什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | @interface MyMethod : NSObject //Instance Method -(int)objAddTwoNum:(int)n1 with:(int)n2; //Class Method +(int)clasAddTwoNum:(int)n1 with:(int)n2; @end @implementation MyMethod -(int)objAddTwoNum:(int)n1 with:(int)n2; { int sum = n1+n2; return sum; } +(int)clasAddTwoNum:(int)n1 with:(int)n2; { int sum = n1+n2; return sum; } @end int main(int argc, const char * argv[]) { @autoreleasepool { //Calculating Execution time for Object method NSDate *startObj = [NSDate date]; [[MyMethod new]objAddTwoNum:30 with:40]; NSDate *finishObj = [NSDate date]; NSTimeInterval executionTimeObj = [finishObj timeIntervalSinceDate:startObj]; NSLog(@"Execution Time OBJ operation: %f", executionTimeObj); //Calculating Execution time for Class method NSDate *startClass = [NSDate date]; [MyMethod clasAddTwoNum:30 with:40]; NSDate *finishClass = [NSDate date]; NSTimeInterval executionTimeClass = [finishClass timeIntervalSinceDate:startClass]; NSLog(@"Execution Time CLass operation: %f", executionTimeClass); } return 0; } |
日志显示类方法的执行时间更短
1 2 3 | 2016-02-04 15:17:01.236 HDMethods[43278:1031682] Execution Time OBJ operation: 0.000028 2016-02-04 15:17:01.236 HDMethods[43278:1031682] Execution Time CLass operation: 0.000002 Program ended with exit code: 0 |
所以我认为在这种情况下,类方法更快
稍后将尝试不同的方法。快乐编码!:)