iOS 5 引入 NSJSONSerialization 原生 API,本文將其與五大主流開源庫進行解析速度橫向評測:
CFAbsoluteTimeGetCurrent() 搭配 NSAutoreleasePool 逐輪計測
// 計時宏
#define RunWithCount(count, description, expr) \
do { \
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); \
for (NSInteger i = 0; i < count; i++) { \
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; \
expr; \
[pool release]; \
} \
CFTimeInterval took = CFAbsoluteTimeGetCurrent() - start; \
NSLog(@"%@ %.3f", description, took); \
} while (0)
// 呼叫範例
JSONTest *test = [[JSONTest alloc] init];
NSInteger count = 100;
[test runWithResourceName:@"twitter_public.json" count:count];
[test runWithResourceName:@"lastfm.json" count:count];
[test runWithResourceName:@"delicious_popular.json" count:count];
[test runWithResourceName:@"yelp.json" count:count];
| 解析器 | twitter_public | lastfm | delicious_popular | yelp |
|---|---|---|---|---|
| SBJSON | 0.335 | 0.691 | 0.506 | 0.361 |
| YAJL | 0.183 | 0.320 | 0.240 | 0.198 |
| TouchJSON | 0.469 | 0.850 | 0.672 | 0.519 |
| JSONKit | 0.130 | 0.212 | 0.207 | 0.155 |
| NextiveJson | 0.164 | 0.280 | 0.234 | 0.186 |
| NSJSONSerialization | 0.113 | 0.177 | 0.168 | 0.140 |

NSJSONSerialization,效能最佳、零依賴、維護成本最低。本測試僅比較解析速度,未涵蓋 API 易用性、記憶體佔用、錯誤處理等維度,實際選型請綜合考量。