我試圖在Android和iOS上爲項目執行SQLite性能之間的基準測試,並且與Android相比,iOS平臺上的性能似乎非常糟糕。Android和iOS上的SQLite之間的性能差異
我想實現的是測量插入SQLite數據庫中的行數(5000)和平臺之間比較的時間。對於Android,我得到500ms左右的結果來執行所有5000次插入,但對於iOS,同樣的操作需要20秒以上。怎麼會這樣?
這是我的iOS代碼(插入部分)片段,dataArray中的是5000個隨機100字符NSString的數組:
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
我沒有Android設備來測試,所以我不知道。但是,我在OS X和Linux上使用SQLite的經驗是,OS X實際上承認了「刷新到磁盤」的請求,這會導致I/O阻塞,而Linux只是一種手動方式,並且不會阻塞。這可能可以解釋它。 – StilesCrisis
我覺得C(iOS)的做法比Java(Android)方式快一點。 –
謝謝。我通過turing的同步獲得了一些速度! – Andain