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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With