0

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?

jr19
  • 92
  • 7

1 Answers1

3

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
cweinberger
  • 3,518
  • 1
  • 16
  • 31
  • Thanks! I'm not actually using the alphabet but "/.@0-9A-Z" so I will use an NSString as this is more memory efficient too. – jr19 Jul 12 '12 at 17:05
  • 2
    Choosing A is like the best case scenario. I get String => 0.098247 | Array => 0.094769 for A BUT for X I get String => 0.396447 | Array => 1.613930. So I guess NSString wins - hurray for NSString. Using your original suggestion I get 0.012515 regardless of position. – Paul.s Jul 12 '12 at 17:07