FMDB性能优化-使用事务提升性能

使用FMDB事务批量更新数据,速度会有大幅度提升。

下面的例子中可以看到,不使用事务,更新374条数据就用了6秒多;而使用事务,仅用了300多毫秒。(iPhone6测试)

不使用事务

FMDatabaseQueue * dbQueue = [SGVFoundationDataCenter shareInstance].dbQueue;    
[dbQueue inDatabase:^(FMDatabase *db) {
    // 清除数据
    NSLog(@"-- add Station begin count = %ld",stations.count);
    [db executeUpdate:@"delete from sgv_station where city_code = ?",@(cityCode)];
    [stations enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SGVSubwayStation * station = obj;
        [db executeUpdate:@"INSERT INTO sgv_station (city_code, line_code, station_code, station_name, line_inner_code, is_wifi_valid) VALUES (?,?,?,?,?,?)",@(cityCode), @(station.lineCode),@(station.stationCode), station.stationName, @(station.lineInnerCode),@(station.isWiFiValid)];
    }];
    NSLog(@"-- add Station end"];
}];

使用事务

FMDatabaseQueue * dbQueue = [SGVFoundationDataCenter shareInstance].dbQueue;    
[dbQueue inDatabase:^(FMDatabase *db) {
    // 清除数据
    NSLog(@"-- add Station begin count = %ld",stations.count);
    [db beginTransaction];
    [db executeUpdate:@"delete from sgv_station where city_code = ?",@(cityCode)];
    [stations enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SGVSubwayStation * station = obj;
        [db executeUpdate:@"INSERT INTO sgv_station (city_code, line_code, station_code, station_name, line_inner_code, is_wifi_valid) VALUES (?,?,?,?,?,?)",@(cityCode), @(station.lineCode),@(station.stationCode), station.stationName, @(station.lineInnerCode),@(station.isWiFiValid)];
    }];
    [db commit];
    NSLog(@"-- add Station end"];
}];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容