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

前端 未结 5 691
醉酒成梦
醉酒成梦 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 04:49

    By default, SqlConnection will use connection pooling. Therefore your code does most likely not actually open many connections in either case.

    You can control if SqlConnection will use pooling by enabling or disabling the pool in the connectionstring, depending on what DB your connection string is for, the syntax will vary.

    See here for some info if you use MSSQLServer. Try setting Pooling=false in the connection string and see if it makes a difference.

    0 讨论(0)
  • 2020-12-01 04:55

    In general, .NET's connection pooling should make it 'not matter' as it does a great job of recycling connections for you. But my practice is to use a single connection for a bunch of transactions I know will be taking place together. I think your timings are an indication of the connection pool doing its job and just plain variations in runs.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-12-01 05:03

    SqlClient will pool your connections. In your first case with one open, it will do the job of opening the connection. Every other run will use the pooled connection. If you reverse your order and do "many connections" first, I would expect you to see the opposite result.

    0 讨论(0)
  • 2020-12-01 05:10

    Definitively, it's better to have one connection. Maybe you are running your benchmark with small amount of data. Try increasing the number to 1,000 or 10,000.

    Another point is that, depending on your app configuration, you might think you are running with multiple connections but .NET is pooling connections for you, so you are basically running with the same connections.

    0 讨论(0)
提交回复
热议问题