Skip to content

Instantly share code, notes, and snippets.

@hfossli

hfossli/main.m

Last active Dec 25, 2015
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@hfossli 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
You can’t perform that action at this time.