Regex vs componentsSeparatedByCharactersInSet
#import <Foundation/Foundation.h> | |
int main(int argc, char *argv[]) { | |
@autoreleasepool { | |
NSUInteger iterations = 1000000; | |
{ // Regex | |
NSTimeInterval timeStart = CFAbsoluteTimeGetCurrent(); | |
NSString *result = nil; | |
for(int i = 0; i < iterations; i++) | |
{ | |
NSString *original = @" Hello this is a long string! "; | |
NSString *squashed = [original stringByReplacingOccurrencesOfString:@"[ ]+" | |
withString:@" " | |
options:NSRegularExpressionSearch | |
range:NSMakeRange(0, original.length)]; | |
result = [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; | |
} | |
NSLog(@"Time spent on %lu iterations %f with result \"%@\"", iterations, CFAbsoluteTimeGetCurrent() - timeStart, result); | |
} | |
{ // Array separation | |
NSTimeInterval timeStart = CFAbsoluteTimeGetCurrent(); | |
NSString *result = nil; | |
for(int i = 0; i < iterations; i++) | |
{ | |
NSString *theString = @" Hello this is a long string! "; | |
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet]; | |
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"]; | |
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces]; | |
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings]; | |
result = [filteredArray componentsJoinedByString:@" "]; | |
} | |
NSLog(@"Time spent on %lu iterations %f with result \"%@\"", iterations, CFAbsoluteTimeGetCurrent() - timeStart, result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Console log
2013-10-18 11:39:54.239 Untitled[33067:707] Time spent on 1000000 iterations 7.679592
2013-10-18 11:40:08.026 Untitled[33067:707] Time spent on 1000000 iterations 13.786276