Android和iOS上的SQLite之间的性能差异

时间:2013-04-18 23:00:47

标签: android ios performance sqlite

我正在尝试在Android和iOS中为项目执行SQLite性能之间的基准测试,并且与Android相比,iOS平台上的性能似乎非常差。

我想要实现的是测量将多行(5000)插入SQLite DB并在平台之间进行比较的时间。对于Android,我得到大约500ms的结果来执行所有5000次插入,但对于iOS,相同的操作需要20秒以上。怎么会这样?

这是我的iOS代码片段(插入部分),dataArray是一个包含5000个随机100个字符的NSStrings的数组:

int numEntries = 5000;
self.dataArray = [[NSMutableArray alloc] initWithCapacity:numEntries];//Array for random data to write to database

//generate random data (100 char strings)
for (int i=0; i<numEntries; i++) {
    [self.dataArray addObject:[self genRandStringLength:100]];
}

// Get the documents directory
NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *docsDir = [dirPaths objectAtIndex:0];

// Build the path to the database file
NSString *databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: @"benchmark.db"]];

NSString *resultHolder = @"";

//Try to open DB, if file not present, create it
if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK){

    sql = @"CREATE TABLE IF NOT EXISTS BENCHMARK(ID INTEGER PRIMARY KEY AUTOINCREMENT, TESTCOLUMN TEXT)";

    //Create table
    if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, NULL) == SQLITE_OK){
        NSLog(@"DB created");
    }else{
        NSLog(@"Failed to create DB");
    }

        //START: INSERT BENCHMARK
        NSDate *startTime = [[NSDate alloc] init];//Get timestamp for insert-timer

        //Insert values in DB, one by one
        for (int i = 0; i<numEntries; i++) {
            sql = [NSString stringWithFormat:@"INSERT INTO BENCHMARK (TESTCOLUMN) VALUES('%@')",[self.dataArray objectAtIndex:i]];
            if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, NULL) == SQLITE_OK){
                //Insert successful
            }
        }

        //Append time consumption to display string
        resultHolder = [resultHolder stringByAppendingString:[NSString stringWithFormat:@"5000 insert ops took %f sec\n", [startTime timeIntervalSinceNow]]];

        //END: INSERT BENCHMARK

Android代码段:

           // SETUP
           long startTime, finishTime;

        // Get database object
            BenchmarkOpenHelper databaseHelper = new BenchmarkOpenHelper(getApplicationContext());
            SQLiteDatabase database = databaseHelper.getWritableDatabase();

            // Generate array containing random data
            int rows = 5000;
            String[] rowData = new String[rows];
            int dataLength = 100;

            for (int i=0; i<rows; i++) {
                rowData[i] = generateRandomString(dataLength);
            }

            // FIRST TEST: Insertion
            startTime = System.currentTimeMillis();

            for(int i=0; i<rows; i++) {
                database.rawQuery("INSERT INTO BENCHMARK (TESTCOLUMN) VALUES(?)", new String[] {rowData[i]});
            }

            finishTime = System.currentTimeMillis();
            result += "Insertion test took: " + String.valueOf(finishTime-startTime) + "ms \n";
            // END FIRST TEST

2 个答案:

答案 0 :(得分:4)

在iOS上,除了StilesCrisis讨论的BEGIN / COMMIT更改(提供最显着的性能差异)之外,如果您想进一步优化iOS性能,请考虑准备SQL一次,然后重复调用sqlite3_bind_textsqlite3_stepsqlite3_reset。在这种情况下,它似乎大约快两倍。

所以,这是我使用sqlite3_exec(使用stringWithFormat%@每次手动构建SQL)对现有iOS逻辑的再现:

- (void)insertWithExec
{
    NSDate *startDate = [NSDate date];

    NSString *sql;

    if (sqlite3_exec(database, "BEGIN", NULL, NULL, NULL) != SQLITE_OK)
        NSLog(@"%s: begin failed: %s", __FUNCTION__, sqlite3_errmsg(database));

    for (NSString *value in dataArray)
    {
        sql = [NSString stringWithFormat:@"INSERT INTO BENCHMARK (TESTCOLUMN) VALUES('%@')", value];
        if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, NULL) != SQLITE_OK)
            NSLog(@"%s: exec failed: %s", __FUNCTION__, sqlite3_errmsg(database));
    }

    if (sqlite3_exec(database, "COMMIT", NULL, NULL, NULL) != SQLITE_OK)
        NSLog(@"%s: commit failed: %s", __FUNCTION__, sqlite3_errmsg(database));

    NSTimeInterval elapsed = [[NSDate date] timeIntervalSinceDate:startDate];

    // log `elapsed` here
}

这里是代码的优化再现,我只准备SQL一次,然后使用sqlite3_bind_text将我们的数据绑定到Android代码使用的SQL中的同一?占位符:

- (void)insertWithBind
{
    NSDate *startDate = [NSDate date];

    if (sqlite3_exec(database, "BEGIN", NULL, NULL, NULL) != SQLITE_OK)
        NSLog(@"%s: begin failed: %s", __FUNCTION__, sqlite3_errmsg(database));

    sqlite3_stmt *statement;

    NSString *sql = @"INSERT INTO BENCHMARK (TESTCOLUMN) VALUES(?)";

    if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) != SQLITE_OK)
        NSLog(@"%s: prepare failed: %s", __FUNCTION__, sqlite3_errmsg(database));

    for (NSString *value in dataArray)
    {
        if (sqlite3_bind_text(statement, 1, [value UTF8String], -1, NULL) != SQLITE_OK)
            NSLog(@"%s: bind failed: %s", __FUNCTION__, sqlite3_errmsg(database));

        if (sqlite3_step(statement) != SQLITE_DONE)
            NSLog(@"%s: step failed: %s", __FUNCTION__, sqlite3_errmsg(database));

        if (sqlite3_reset(statement) != SQLITE_OK)
            NSLog(@"%s: reset failed: %s", __FUNCTION__, sqlite3_errmsg(database));
    }

    sqlite3_finalize(statement);

    if (sqlite3_exec(database, "COMMIT", NULL, NULL, NULL) != SQLITE_OK)
        NSLog(@"%s: commit failed: %s", __FUNCTION__, sqlite3_errmsg(database));

    NSTimeInterval elapsed = [[NSDate date] timeIntervalSinceDate:startDate];

    // log `elapsed` here
}

在我的iPhone 5上,使用sqlite3_exec逻辑(我的insertWithExec方法)插入5,000条记录需要280-290毫秒,插入相同的5,000条记录需要110-127毫秒{{1 }},sqlite3_bind_textsqlite3_step(我的sqlite3_reset方法)。我的数字与你的数字不可比(不同的设备,插入不同的insertWithBind对象,我在后台队列中做了它等),但值得注意的是,在准备SQL语句时花费的时间不到一半一次,然后只重复绑定,步骤和重置调用。

看一下Android代码,我注意到你正在使用dataValues占位符,所以我认为它也在幕后进行?(虽然我不知道它是否正在准备它每次都有一次绑定/步进/重置,或者每次重新准备;可能是后者)。


顺便说一句,作为一般经验法则,您应该像在Android中一样使用sqlite3_bind_text占位符,而不是使用?手动构建SQL,因为它可以帮助您需要在数据中手动转义撇号,保护您免受SQL注入攻击等。

答案 1 :(得分:2)

您需要使用交易 - 首先执行BEGIN并以COMMIT结束。

这应该会大大提高INSERT的效果。

http://www.titaniumdevelopment.com.au/blog/2012/01/27/10x-faster-inserts-in-sqlite-using-begin-commit-in-appcelerator-titanium-mobile/

一旦完成,我预计在两个平台上都会有5000个插件非常快。

这是另一个StackOverflow答案,其中列出了大量可以提高SQLite性能的不同内容,包括使用绑定变量和启用各种PRAGMA模式,这些模式牺牲了速度的稳健性:Improve INSERT-per-second performance of SQLite?