Dapper插入记录性能测试

最近学习了Dapper,听说它里面有批量插记录的功能,就写了个小程序来测试下:分别用SqlBulkCopay,原始的单条插入,Dapper批量插入5万条记录。

表结构 tb_User (id, UserName,Password)

比较结果如下:

1.Dapper: 花费时间10秒

 public void TesDappertBatch()
        {
            IDbConnection connection = new SqlConnection(_connect);
            connection.Open();
            var tran = connection.BeginTransaction(IsolationLevel.Serializable);
            var userList=Enumerable.Range(1, 50000).Select(i => new User
            {
                UserName = "User" + i,
                Password="pwd"+i

            });
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var result = connection.Execute("insert tb_User(UserName,Password) values(@UserName,@Password)", userList,tran);
            tran.Commit();
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            Console.ReadLine();//10023

        }


2.SqlBulkCopy,我用的是自己封闭的SqlBulkHelper,花费1.5秒

 public void TestBulk()
        {
            BulkCopyHelper bh = new BulkCopyHelper(_connect);
            DataTable dt = new DataTable();
            dt.Columns.Add("UserName", typeof(string));
            dt.Columns.Add("PassWord", typeof(string));
            for(int i=0;i<50000;i++)
            {
                dt.Rows.Add(new object[] { "User" + i, "pwd" + i });
            }
            
            bh.SetMappingList(dt);
            bh.DestTable = "tb_User";
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            bh.BulkInsert(dt);
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);

            Console.ReadLine(); //1551

            
        }

3.原生SQL单条插入,花费60秒

   public void TestSingInsert()
        {
            
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i=0;i< 50000;i++)
            {
                string sql = @"
insert tb_User(UserName,PassWord) values(@p1,@p2)
";
                string user = "User" + i;
                string pwd = "Pwd" + i;
                SqlHelper.ExecuteNonQuery(_connect, CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@p1", user),new SqlParameter("@p2",pwd )});
            }

            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);

            Console.ReadLine(); //60469
        }

如此看来,虽然性能还不能和SqlBulkCopy比,但也相当不错了,而且还可以用在SqlServer以外的数据库上。在非批量导入(Excel,其它数据表),且不是单条操作的场景下适宜使用。单条操作我还是用自己的ORMapping数据模型更方便,因为Dapper需要自己手工写类。

你可能感兴趣的:(c#)