Dispose the connection or Close the connection

Anyname Donotcare picture Anyname Donotcare · Jul 12, 2012 · Viewed 15.9k times · Source

Which one of the following two methods has better performance ?

using( var DB_Connection_s = new DBConnection() )
{
 //todo: interact with database connection
}

or just :

DB_Connection_s.Close();

at the end.

Does the first method make the pooling concept useless? Because if I dispose the connection with each use, then I have to open a new connection every time (and there won't be any connections in the pool).

Answer

Felice Pollano picture Felice Pollano · Jul 12, 2012

The using pattern is better, since the Dispose call closes the connection anyway, but as a bonus the connection is closed even if something inside the using goes wrong. For example an exception or just a return that forces the program execution to go out of the using scope. With a using, you don't need to explicitly close the connection, which makes the code more readable. As an another pattern, the connection must be closed as soon as possible. There is no performance drawback in closing/opening the connection too frequently, because the connection pool will optimize the connection re-using for you.