NSJSONSerialization 与 NSKeyedArchiver进行数据持久化性能比较

在选择持久化方案时,系统提供的NSJSONSerialization要比NSKeyedArchiver在效率和体积上更优,做如下测试:
1、首先新建一个 plist文件(过程不做详述):如下图所示


NSJSONSerialization 与 NSKeyedArchiver进行数据持久化性能比较_第1张图片
plist.png

2、新建 person 类 (过程不做详述)

#import 

@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、比较性能,测试代码如下

- (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);
}

结果如下图:NSJSONSerialization用时0.59秒,而NSKeyedArchiver用时4.007秒

NSJSONSerialization测试结果.png

NSKeyedArchiver测试结果.png

可以看出两者的序列化速度是有质的差别的。

你可能感兴趣的:(NSJSONSerialization 与 NSKeyedArchiver进行数据持久化性能比较)