做app的时候,总免不了要多次遍历数组或者字典。
究竟哪种遍历方式比较快呢?我做了如下测试:
首先定义测试用宏:
1
2
3
4
5
6
7
8
9
|
#define
NSTimeInterval
NSLog (@ "MULogTimeintervalBegin:%@" ,
#define
start
NSLog (@ "%@:%f" ,
duration
#define
|
接着编写测试代码:
NSarray:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
- void )testArray
{
NSMutableArray * NSMutableArray
for
NSInteger
[testArray NSString
"%ld" ,
}
NSLog (@ "init:%ld" ,
__block NSMutableString * NSMutableString
MULogTimeintervalBegin(@ "ArrayTest" );
NSUInteger
for
NSInteger
[sum
}
[sum "" ];
MULogTimeintervalPauseAndLog(@ "for );
for ( NSString *
[sum
}
[sum "" ];
MULogTimeintervalPauseAndLog(@ "for-in" );
[testArray id
NSUInteger
BOOL
[sum
}];
[sum "" ];
MULogTimeintervalPauseAndLog(@ "enumerateBlock" );
}
|
NSDictionary:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
- void )testDictionary
NSMutableDictionary * NSMutableDictionary
for
NSInteger
[testDic "test"
NSString
"%ld" ,
}
NSLog (@ "init:%ld" ,
__block NSMutableString * NSMutableString
MULogTimeintervalBegin(@ "DictionaryTest" );
for
NSString *
[sum
}
[sum "" ];
MULogTimeintervalPauseAndLog(@ "for );
for
id
[sum
}
[sum "" ];
MULogTimeintervalPauseAndLog(@ "for );
[testDic id
id
BOOL
[sum
}
MULogTimeintervalPauseAndLog(@ "enumeration" );
}
|
下面是测试结果:
Test Case '-[LoopTestTests testArray]' started.
2012-08-02 17:14:22.061 otest[388:303] init:100000
2012-08-02 17:14:22.062 otest[388:303] MULogTimeintervalBegin:ArrayTest
2012-08-02 17:14:22.075 otest[388:303]for statement:0.013108
2012-08-02 17:14:22.083 otest[388:303]for-in:0.008186
2012-08-02 17:14:22.095 otest[388:303] enumerateBlock:0.012290
Test Case '-[LoopTestTests testArray]' passed (0.165 seconds).
Test Case '-[LoopTestTests testDictionary]' started.
2012-08-02 17:14:22.273 otest[388:303] init:100000
2012-08-02 17:14:22.274 otest[388:303] MULogTimeintervalBegin:DictionaryTest
2012-08-02 17:14:22.284 otest[388:303] for statement allValues:0.010566
2012-08-02 17:14:22.307 otest[388:303] for statement allKeys:0.022377
2012-08-02 17:14:22.330 otest[388:303] enumeration:0.023914
Test Case '-[LoopTestTests testDictionary]' passed (0.217 seconds).
可以看出对于数组来说,for-in方式遍历速度是最快的,普通风格的for和block方式速度差不多。对于字典来说,allValues方式遍历最快,allKeys和block差不多。
那么,为什么会这样呢?
NSArray:
1
2
3
|
for
NSInteger
[sum
}
|
这里由于存在:[objectAtIndex:i]这样的取操作,所以速度会有所下降。
而
1
2
3
|
for ( NSString *
[sum
}
|
尽管也有取操作,但是绕开了oc的message机制,速度会快一点。也有可能是编译器为了for-in作了优化。
block为什么会慢一些这个有待研究。
NSDictionary:
1
2
3
|
for
id
[sum
}
|