Keith said:
I read in a Visual Studio .NET book that with C# it is now recommended to
open database connections whenever you need to query a database as opposed
to the traditional method of opening a database at the start of your app and
closing it at the end.
I recently profiled the expense of creating and opening connections on
the fly using intel vTune. One method I profiled looked sort of like this:
DataSet Load(int x)
{
using(IDbConnection con = Factory.CreateConnection())
{
conn.Open();
DataSet result = new DataSet();
IDbDataAdapter adapter1, adapter2;
// initialize adapters and sql text using x and conn
adapter1.Fill(result);
adapter2.Fill(result);
return result;
}
}
Everytime a certain form opened, this routine was called about 200 times
(in a background thread, FWIW). The execution profile of Load broke down
like this:
total time spent inside this method: 7.397 s
execution count : 273
adapter1.Fill -> 3.814 s == 51.6%
adapter2.Fill -> 2.714 s == 36.7%
conn.Open -> 0.841 s == 11.4%
avg time to open connection : 3.0 ms
Both queries utilized an index on the table. Each datatable had on
average about 50 rows and 6 columns.
Based on the results that I saw, I agree with the "Just create
connections on the fly" philosophy, but don't create them over and over
again in a loop, if you can avoid it.
Creating them on the fly can also make life easier in other ways. First,
it makes it easier to write a using statement to dispose the connection.
Also, if you are writing a multithreaded app, you won't make the mistake
of using the same connection in two threads at the same time. My Load
method can be called from multiple threads without worrying about
synchronization issues.
H^2