Skip to content

Instantly share code, notes, and snippets.

@hfossli
Last active December 25, 2015 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hfossli/7039131 to your computer and use it in GitHub Desktop.
Save hfossli/7039131 to your computer and use it in GitHub Desktop.
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);
}
}
}
@hfossli
Copy link
Author

hfossli commented Oct 18, 2013

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment