SQLite速度評測代碼

來源:互聯網
上載者:User


今天有個朋友測試 SQLite,然後得出的結論是:SQLite 效率太低,批量插入1000條記錄,居然耗時 2 分鐘!
下面是他發給我的測試代碼。我暈~~~~~~

using System.Data;
using System.Data.Common;
using System.Data.SQLite;

// 建立資料庫檔案
File.Delete("test1.db3");
SQLiteConnection.CreateFile("test1.db3");

DbProviderFactory factory = SQLiteFactory.Instance;
using (DbConnection conn = factory.CreateConnection())
{
// 串連資料庫
conn.ConnectionString = "Data Source=test1.db3";
conn.Open();

// 建立資料表
string sql = "create table [test1] ([id] INTEGER PRIMARY KEY, [s] TEXT COLLATE NOCASE)";
DbCommand cmd = conn.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();

// 添加參數
cmd.Parameters.Add(cmd.CreateParameter());

// 開始計時
Stopwatch watch = new Stopwatch();
watch.Start();

// 連續插入1000條記錄
for (int i = 0; i < 1000; i++)
{
cmd.CommandText = "insert into [test1] ([s]) values (?)";
cmd.Parameters[0].Value = i.ToString();

cmd.ExecuteNonQuery();
}

// 停止計時
watch.Stop();
Console.WriteLine(watch.Elapsed);
}

哎~~~~ 一個常識性的錯誤,我加幾行代碼 (新增代碼標記 "// <-------------------")。

using System.Data;
using System.Data.Common;
using System.Data.SQLite;

// 建立資料庫檔案
File.Delete("test1.db3");
SQLiteConnection.CreateFile("test1.db3");

DbProviderFactory factory = SQLiteFactory.Instance;
using (DbConnection conn = factory.CreateConnection())
{
// 串連資料庫
conn.ConnectionString = "Data Source=test1.db3";
conn.Open();

// 建立資料表
string sql = "create table [test1] ([id] INTEGER PRIMARY KEY, [s] TEXT COLLATE NOCASE)";
DbCommand cmd = conn.CreateCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();

// 添加參數
cmd.Parameters.Add(cmd.CreateParameter());

// 開始計時
Stopwatch watch = new Stopwatch();
watch.Start();

DbTransaction trans = conn.BeginTransaction(); // <-------------------
try
{
// 連續插入1000條記錄
for (int i = 0; i < 1000; i++)
{
cmd.CommandText = "insert into [test1] ([s]) values (?)";
cmd.Parameters[0].Value = i.ToString();

cmd.ExecuteNonQuery();
}

trans.Commit(); // <-------------------
}
catch
{
trans.Rollback(); // <-------------------
throw; // <-------------------
}

// 停止計時
watch.Stop();
Console.WriteLine(watch.Elapsed);
}

執行一下,耗時 0.2 秒。這差距是不是太大了點?

為什麼只是簡單啟用了一個事務會有這麼大的差距呢?很簡單,SQLite 預設為每個操作啟動一個事務,那麼原代碼 1000 次插入起碼開啟了 1000 個事務,"事務開啟 + SQL 執行 + 事務關閉" 自然耗費了大量的時間,這也是後面顯示啟動事務後為什麼如此快的原因。其實這是資料庫操作的基本常識,大家要緊記,不好的代碼效率差的不是一點半點鐘。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.