Is it better to execute many sql commands with one connection, or reconnect every time?

前端 未结 5 708
醉酒成梦
醉酒成梦 2020-12-01 04:11

Here\'s my test code, which seems to suggest that it\'s better to connect multiple times instead of connecting just once.

Am I doing something wrong?



        
5条回答
  •  爱一瞬间的悲伤
    2020-12-01 05:00

    Since .NET reuses connections ("connection pooling"), there is not much overhead in creating a new instance of DbConnection several times in a row. ADO.NET will just reuse the connection under the hood. That's why it's good you are disposing the SqlConnection object each time, telling .NET that it can return it to the pool.

    You can, however, increase performance of multiple inserts by using ADO.NET batching. In that case you can easily have several thousands of inserts per second. If performance is critical, you can even consider using SQLBulkCopy.

    Also, your first pair of results is quite strange: 30s for 100 inserts?

提交回复
热议问题