快速示例时间为什么您应该做正确的事情而不是“错误”。这是在 ICS 4.0.4 上运行的测试,它具有可怕的 INSERT 性能。
首先,一个简单的方法SQLiteOpenHelper
是创建一个UNIQUE
对列有约束的表,以导致不时发生冲突。
class SimpleHelper extends SQLiteOpenHelper {
// InsertHelpers are a really good idea - they format a prepared statement
// for you automatically.
InsertHelper mInsert;
public SimpleHelper(Context context) {
super(context, "tanika.db", null, 1);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
mInsert = new InsertHelper(db, "target");
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE target (\n" +
"_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
"val1 TEXT NOT NULL,\n" +
"val2 TEXT NOT NULL,\n" +
"val3 TEXT NOT NULL,\n" +
// Let's make one unique so we can get some juicy conflicts
"val4 TEXT NOT NULL UNIQUE\n" +
")");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
捆绑在任何旧的Activity
我们添加以下简单的测试方法:
long test(final int n) {
long started = System.currentTimeMillis();
ContentValues values = new ContentValues();
for (int i = 0; i < n; i++) {
values.clear();
// Every 20th insert, generate a conflict in val4
String val4 = String.valueOf(started + i);
if (i % 20 == 0) {
val4 = "conflict";
}
values.put("val1", "Value1");
values.put("val2", "Value2");
values.put("val3", "Value3");
values.put("val4", val4);
mHelper.mInsert.replace(values);
}
return System.currentTimeMillis() - started;
}
如您所见,这将导致每 20 次INSERT
左右发生一次冲突。调用InsertHelper#replace(..)
会导致助手使用 a INSERT OR REPLACE
on 冲突。
现在,让我们在没有围绕它的事务的情况下运行带有 & 的测试代码。
class Test1 extends AsyncTask<Integer, Void, Long> {
@Override
protected Long doInBackground(Integer... params) {
return test(params[0]);
}
@Override
protected void onPostExecute(Long result) {
System.out.println(getClass().getSimpleName() + " finished in " + result + "ms");
}
}
class Test2 extends AsyncTask<Integer, Void, Long> {
protected Long doInBackground(Integer... params) {
SQLiteDatabase db = mHelper.getWritableDatabase();
db.beginTransaction();
long started = System.currentTimeMillis();
try {
test(params[0]);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
return System.currentTimeMillis() - started;
}
@Override
protected void onPostExecute(Long result) {
System.out.println(getClass().getSimpleName() + " finished in " + result + "ms");
}
}
一切都是这样开始的:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHelper = new SimpleHelper(this);
mHelper.getWritableDatabase(); // Forces the helper to initialize.
new Test1().execute(2055);
new Test2().execute(2055);
}
结果呢?如果没有事务,则INSERT
s 需要41072ms。对于事务,它们需要940ms。总之,FFS,开始使用InsertHelper
s和事务。