Last active
December 25, 2015 20:59
-
-
Save hfossli/7039131 to your computer and use it in GitHub Desktop.
Regex vs componentsSeparatedByCharactersInSet
This file contains 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
#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
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