在選擇持久化方案時(shí),系統(tǒng)提供的NSJSONSerialization要比NSKeyedArchiver在效率和體積上更優(yōu)继阻,做如下測(cè)試:
1闪水、首先新建一個(gè) plist文件(過(guò)程不做詳述):如下圖所示
2割择、新建 person 類(lèi) (過(guò)程不做詳述)
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, copy)NSString * name;
@property (nonatomic, copy)NSString * age;
@property (nonatomic, copy)NSString * height;
@property (nonatomic, copy)NSString * weight;
@property (nonatomic, copy)NSString * sex;
+ (instancetype)personWithDic:(NSDictionary *)dic;
- (NSDictionary *)dic;
@end
#import "Person.h"
@implementation Person
- (NSDictionary *)dic
{
return @{
@"name":self.name,
@"age":self.age,
@"height":self.height,
@"weight":self.weight,
@"sex":self.sex
};
}
+ (instancetype)personWithDic:(NSDictionary *)dic
{
Person * person = [[Person alloc] init];
person.name = dic[@"name"];
person.age = dic[@"age"];
person.height = dic[@"height"];
person.weight = dic[@"weight"];
person.sex = dic[@"sex"];
return person;
}
@end
3嘿辟、比較性能藕各,測(cè)試代碼如下
- (void)viewDidLoad {
[super viewDidLoad];
NSString * path = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"plist"];
NSArray * ary = [NSArray arrayWithContentsOfFile:path];
Person * person = [Person personWithDic:[ary lastObject]];
NSMutableArray * personsData = [@[] mutableCopy];
NSLog(@"%zd", personsData.count);
for (int i = 0; i < 100000; i++) {
[personsData addObject:[NSJSONSerialization dataWithJSONObject:[person dic] options:0 error:nil]];
}
NSLog(@"%zd", personsData.count);
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString * path = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"plist"];
NSArray * ary = [NSArray arrayWithContentsOfFile:path];
Person * person = [Person personWithDic:[ary lastObject]];
NSMutableArray * personsData = [@[] mutableCopy];
NSLog(@"%zd", personsData.count);
for (int i = 0; i < 100000; i++) {
[personsData addObject:[NSKeyedArchiver archivedDataWithRootObject:[person dic]]];
}
NSLog(@"%zd", personsData.count);
}
結(jié)果如下圖:NSJSONSerialization用時(shí)0.59秒池摧,而NSKeyedArchiver用時(shí)4.007秒
可以看出兩者的序列化速度是有質(zhì)的差別的。