為了清楚的了解NO-SQL和SQL的效能差異,所以進行了寫入及讀取的效能測試,測試用的電腦則為我的筆電,規格如下:
CPU:Intel Core i7-2630QM
RAM:8GB
OS:Windows 7 Home Premium
HD:Memoright SSD 240G
測試結果可以發現差異非常大喔!MongoDB比MS-SQL速度快上10倍,不過還是需要看個人需求選擇適當的資料庫,以下提供參考。
MongoDB 測試結果:
以下為 MongoDB 測試用的程式碼:
int RunNum = 100000; var mongo = new Mongo("mongodb://127.0.0.1"); mongo.Connect(); var TEST_DB = mongo.GetDatabase("TEST_DB"); var TEST_TABLE = TEST_DB.GetCollection("TEST"); Stopwatch sw = new Stopwatch(); //寫入資料 sw.Reset(); sw.Start(); for (int i = 0; i < RunNum; i++) { TEST_TABLE.Insert(new Document() { { "ID", i }, { "City", "Taiwan" } }); } sw.Stop(); Console.WriteLine(); Console.WriteLine("MongoDB 寫入 " + RunNum.ToString() + " 次時間:" + sw.ElapsedMilliseconds.ToString() + "/ms"); //唯一索引 TEST_TABLE.MetaData.CreateIndex(new Document() { { "ID", 1 } }, true); System.Threading.Thread.Sleep(10000); //讀取資料 sw.Reset(); sw.Start(); for (int i = 0; i < RunNum; i++) { var city = TEST_TABLE.FindOne(new Document() { { "ID", i } })["City"]; } sw.Stop(); Console.WriteLine(); Console.WriteLine("MongoDB 讀取 " + RunNum.ToString() + " 次時間:" + sw.ElapsedMilliseconds.ToString() + "/ms");
MS-SQL 測試結果:
以下為 MS-SQL 測試用的程式碼:
int RunNum = 100000; Stopwatch sw = new Stopwatch(); SqlConnection con = new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};Persist Security Info={2};User ID={3};Password={4}", "127.0.0.1", "TEST", "True", "TEST", "TEST")); con.Open(); //寫入資料 sw.Reset(); sw.Start(); for (int i = 0; i < RunNum; i++) { SqlCommand SQL_Insert = new SqlCommand("Insert Into TEST (\"ID\",\"City\") values (" + i.ToString() + ",'Taiwan')", con); SQL_Insert.ExecuteNonQuery(); SQL_Insert.Dispose(); } sw.Stop(); Console.WriteLine(); Console.WriteLine("MS-SQL 寫入 " + RunNum.ToString() + " 次時間:" + sw.ElapsedMilliseconds.ToString() + "/ms"); //讀取資料 sw.Reset(); sw.Start(); for (int i = 0; i < RunNum; i++) { DataSet DS = new DataSet(); SqlDataAdapter DT = new SqlDataAdapter(new SqlCommand("SELECT * FROM TEST WHERE ID = " + i.ToString(), con)); DT.Fill(DS); DT.Dispose(); string city = DS.Tables[0].Rows[0]["City"].ToString(); } sw.Stop(); Console.WriteLine(); Console.WriteLine("MS-SQL 讀取 " + RunNum.ToString() + " 次時間:" + sw.ElapsedMilliseconds.ToString() + "/ms"); con.Close(); con.Dispose(); con = null;
本文章網址:
https://www.ez2o.com/Blog/Post/MongoDB-And-MS-SQL-Benchmarks
https://www.ez2o.com/Blog/Post/314
https://www.ez2o.com/Blog/Post/MongoDB-And-MS-SQL-Benchmarks
https://www.ez2o.com/Blog/Post/314