我正在尝试为一个项目在 Android 和 iOS 中的 SQLite 性能之间执行基准测试,并且与 Android 相比,在 iOS 平台上的性能似乎非常差。
我想要实现的是测量将多行(5000)插入 SQLite DB 并在平台之间进行比较的时间。对于 Android,执行所有 5000 次插入需要大约 500 毫秒的结果,但对于 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
安卓代码片段:
// 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