我试图在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
[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
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
rowData[i] = generateRandomString(dataLength);
}
// FIRST TEST: Insertion
startTime = System.currentTimeMillis();
for(int i=0; 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
解决方法:
您需要使用事务 – 首先执行BEGIN并使用COMMIT结束.
这应该会大大提高INSERT的性能.
一旦完成,我预计在两个平台上都会有5000个插件非常快.
这是另一个StackOverflow答案,其中列出了大量可以提高SQLite性能的不同内容,包括使用绑定变量和启用各种PRAGMA模式,这些模式可以提高速度的稳健性:Improve INSERT-per-second performance of SQLite?
标签:android,performance,ios,sqlite
来源: https://codeday.me/bug/20190825/1722435.html