JamesNT
JamesNT

Reputation: 57

Opening and closing connections to SQL Server

I am working in a small team of about a dozen developers on a project being written in C# WPF as the infrastructure/dba. As I run traces against the SQL Server to see how performance is going, what I am seeing is a constant:

open connection run some statement close connection exec sp_reset_connection

open connection run some statement close connection exec sp_reset_connection

open connection run some statement close connection exec sp_reset_connection

And so on and on and on. I have spoke with the devs about this and some have mentioned possible situations where a foreach loop may be encompassing a using statement so a foreach through a datatable would open and close connections throughout the contents of the datatable.

Question: Is getting better control of the constant opening and closing of connections a worthy goal or are connections really that cheap? My logic is that while opening and closing a connection may relatively be cheap, nothing is cheap when done in sufficiently large numbers.

Details:

Upvotes: 1

Views: 238

Answers (3)

oleksii
oleksii

Reputation: 35935

If performance is an issue, but you don't want to refactor code you should consider setting a ConnectionPooling = true in the connections string.

Connection pooling allows one to keep physical connection, which is generally expensive to setup, while disposing logical connection.

Upvotes: 0

MeanGreen
MeanGreen

Reputation: 3315

Opening and closing connections to a database are relatively expensive, as can be read in detail here: Performance Considerations (Entity Framework), but I think the same concept mostly applies without EF. During loops, it's usually not recommended to open and close the connection every time, but instead open it, process all rows and close the connection.

The answer would be to let the using encompass the loop, instead of the other way around. If performance is relevant (it almost always is), it definately pays to put effort into efficiënt data access, especially early in the development process.

Upvotes: 0

L-Four
L-Four

Reputation: 13551

If you use entity framework, you should create the context just before you need it and dispose it as soon as possible:

using (var someContext = new SomeContext())
{

}

The reason is to avoid memory building up and to avoid thread-safety issues.

Of course, don't do this in a loop - this is at the level of a request.

Upvotes: 1

Related Questions