본문 바로가기

code snippet

[iOS] NSString과 NSMutableString을 이용한 append 속도 비교

간단하게 A에서 z까지 문자열 결합 속도 테스트.. 약 60번 append 메소드가 실행된다.

NSString의 stringByAppending~~과 NSMutableString의 append를 비교했다. NSString은 매번 객체를 생성하는 방식이므로 느릴것이다~라고 예상.

-(void)testAppend1 {

NSString *result = @"";

NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];

for (char c = 'A' ; c <= 'z'; c++) {

result = [result stringByAppendingFormat:@"%c", c];

}

NSLog(@"Result of NSString with stringByAppendingFormate : time : %f", [NSDate timeIntervalSinceReferenceDate] - start);

}


-(void)testAppend2 {

NSMutableString *result = [NSMutableString string];

NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];

for (char c = 'A' ; c <= 'z'; c++) {

[result appendFormat:@"%c", c];

}

NSLog(@"Result of NSMutable with append method : time : %f", [NSDate timeIntervalSinceReferenceDate] - start);

}


기기에서 돌린 결과, NSMutableString을 이용한 방식이 약 20배 이상 빠르다.

매번 결과가 달라지긴 하다만..

Result of NSString with stringByAppendingFormate : time : 0.011139

Result of NSMutable with append method : time : 0.000614






반응형