2012-07-12 52 views
0

有誰知道在NSString或相同字符的NSArray中查找字符的速度更有效嗎?字符在NSString中的位置與NSArray - 性能/效率

我想知道哪個具有最好和最有效的算法來找到正確的值。

我真的很想找到字母在字母表中的位置。例如在字母表中找到「E」的位置@"ABCDE....XYZ"[NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",...,@"X",@"Y",@"Z"];

哪個更適合搜索? NSString或NSArray?

+0

爲什麼要使用對象? 'NSLog(@「%d」,toupper('E') - 64);' – 2012-07-12 16:54:34

回答

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 
+0

謝謝! 我實際上並沒有使用字母表,而是使用了「/[email protected]」,所以我會使用NSString,因爲這也是更高效的內存。 – jr19 2012-07-12 17:05:23

+2

選擇A就像是最好的情況。我得到了String => 0.098247 | Array => 0.094769 for A BUT for X我得到String => 0.396447 | Array => 1.613930。所以我猜NSString贏了 - 爲NSString歡呼。使用你的原始建議,無論位置如何,我都會得到0.012515。 – 2012-07-12 17:07:33

+0

好點,保羅! – cweinberger 2012-07-12 17:08:25