Question

Does anyone know what is more efficient with regards to speed for finding a character in an NSString or in an NSArray of the same characters?

I want to know which has the best and most efficient algorithm to find the correct value.

I effectively want to find the position of a character in the alphabet. e.g. find the position of "E" in the alphabet @"ABCDE....XYZ" or [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",...,@"X",@"Y",@"Z"];

Which is the better one to search through? NSString or NSArray?

Was it helpful?

Solution

If it's just A-Z:

NSString *string = @"A";
int position = (int)[string characterAtIndex:0]-64;
NSLog(@"%d", position);

Just out of curiosity:

NSString *alphabetString = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSMutableArray *alphabetArray = [NSMutableArray array];
for(int pos = 0; pos < [alphabetString length]; pos++) {

    [alphabetArray addObject:[alphabetString substringWithRange:NSMakeRange(pos, 1)]];
}

NSString *check = @"A";

// check with rangeOfString
NSDate *start = [NSDate date];
for(int i = 0; i < 1000000; i++) {

    int position = [alphabetString rangeOfString:check].location + 1;
}
NSDate *end = [NSDate date];
NSLog(@"STRING | time needed: %f", [end timeIntervalSinceDate:start]);

// check with indexOfObject
start = [NSDate date];
for(int i = 0; i < 1000000; i++) {

    int position = [alphabetArray indexOfObject:check] + 1;
}
end = [NSDate date];
NSLog(@"ARRAY | time needed: %f", [end timeIntervalSinceDate:start]);

// check with ASCII position
start = [NSDate date];
for(int i = 0; i < 1000000; i++) {

    int position = (int)[check characterAtIndex:0]-64;
}
end = [NSDate date];
NSLog(@"ASCII | time needed: %f", [end timeIntervalSinceDate:start]);

Console:

STRING | time needed: 0.156067
ARRAY | time needed: 0.213297
ASCII | time needed: 0.017055
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top