Remove the connection or close the connection

Which of the following two methods has the best performance?

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

or simply:

 DB_Connection_s.Close(); 

in the end.

Does the first method make the concept of unification useless? Because if I establish a connection with each use, I have to open a new connection every time (and there will be no connections in the pool).

+7
source share
4 answers

Connections are returned back to the pool when you call Close or Dispose in Connection ...

source = SQL Server Connection Pool (ADO.NET)

So, remove all performance loss issues caused by missing pool connections.
From a code point of view, the difference should be so minimal that you should always use the using statement

+5
source

The using pattern is better, since calling Dispose closes the connection anyway, but as a bonus, the connection is closed, even if something inside the use goes wrong. For example, an exception or just a return that causes program execution to go out of scope. When using, you do not need to explicitly close the connection, which makes the code more readable. Like another template, the connection should be closed as soon as possible. Lack of performance when closing / opening a connection is too common because the connection pool optimizes reuse of the connection for you.

+7
source

Use Dispose. Internally, inside Dispose, it will close the connection, so you don’t have to worry, this can be easily checked using Reflector or similar, if in doubt.

Regarding performance, I would still work using. Windows has various caches included (of course, in ODBC) to provide reuse for repeated requests to the same connection, and therefore you don't need to worry about performance.

+1
source

If you haven't called .Open () again,

use the using(){} block.

if you intend to use the same connection soon,
call .close(); , then .open() and so on ...
save your IDisposable class and delete the connection there!

it still takes time to create a Connection object

+1
source

All Articles