Note that there are some explanatory texts on larger screens.

plurals
  1. POADO.Net: reuse open SqlConnection or get a new one every time?
    primarykey
    data
    text
    <p>Before posting this question, I have read several answers on this site: <a href="https://stackoverflow.com/questions/8649096/open-connection-before-every-single-nonquery-or-one-connection-for-the-whole">like this</a> and <a href="https://stackoverflow.com/questions/9807268/is-it-best-to-pass-an-open-sqlconnection-parameter-or-call-a-new-one-in-each-me">this</a>. Everyone seem to agree that "c# application pools are optimized for multiple calls to the same database." </p> <p>However, I still observe a substantial performance penalty if I get a connection from the pool. Here are my benchmarks:</p> <pre><code> private const string localConnString = "Data Source=(local);Integrated Security=SSPI;database=MyTest;Pooling=true"; [Test] public void GetNewConnectionEveryTime() { var stopwatch = new Stopwatch(); stopwatch.Start(); for (var i = 0; i &lt; 1000; i++) { using (var conn = new SqlConnection(localConnString)) { conn.Open(); const string saveTrancount = "EXEC dbo.TestTran"; ExecuteSql(conn, saveTrancount); } } stopwatch.Stop(); Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); //Time elapsed: 00:00:00.5576016 } [Test] public void ReuseOneConnection() { var stopwatch = new Stopwatch(); stopwatch.Start(); using (var conn = new SqlConnection(localConnString)) { conn.Open(); for (var i = 0; i &lt; 1000; i++) { const string saveTrancount = "EXEC dbo.TestTran"; ExecuteSql(conn, saveTrancount); } } stopwatch.Stop(); Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); //Time elapsed: 00:00:00.1110324 } private void ExecuteSql(SqlConnection conn, string sql, int timeout = 0) { var command = conn.CreateCommand(); command.CommandText = sql; command.CommandType = CommandType.Text; command.CommandTimeout = timeout; command.ExecuteNonQuery(); } </code></pre> <p>Apparently getting a connection from the pool takes four times more time (00:00:00.5576016 - 00:00:00.1110324 appr 0.44) than doing actual work (00:00:00.1110324 in second benchmark). What am I missing? </p> <p>Edit: I am running these benchmarks against a database created on RAM Disk, so all my database operations are very fast.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload