有没有人知道在NSString或相同字符的NSArray中查找字符的速度更有效?
我想知道哪种算法具有最佳和最有效的算法来找到正确的值。
我实际上想要找到字母表中字符的位置。例如在字母E
或@"ABCDE....XYZ"
[NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",...,@"X",@"Y",@"Z"];
”的位置
哪个搜索更好? NSString或NSArray?
答案 0 :(得分:3)
如果它只是A-Z:
NSString *string = @"A";
int position = (int)[string characterAtIndex:0]-64;
NSLog(@"%d", position);
出于好奇:
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]);
控制台:
STRING | time needed: 0.156067
ARRAY | time needed: 0.213297
ASCII | time needed: 0.017055