Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispose the connection or Close the connection

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).

like image 476
Anyname Donotcare Avatar asked Jul 12 '12 09:07

Anyname Donotcare


2 Answers

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.

like image 148
Felice Pollano Avatar answered Sep 20 '22 13:09

Felice Pollano


Connections are released back into the pool when you call Close or Dispose on the Connection...

source = SQL Server Connection Pooling (ADO.NET)

So, remove any worry about performance loss caused by missed pooled connections.
From the code standpoint the difference should be so minimal that the using statement should always be used

like image 38
Steve Avatar answered Sep 19 '22 13:09

Steve