Reputation: 51064
My code is littered with using
blocks that instantiate, use, and dispose a DbContext
object. Would it improve performance any if I passed an open connection to the constructors of these objects, or does connection pooling do enough work for me on that front?
Upvotes: 2
Views: 1069
Reputation: 41769
It would depend on the database system you address, and wheter the ADO.NET provider supports conection pooling for that particular database system.
Answer to your question: For SQL Server, no, but for SQL Server Compact, yes.
Upvotes: 2
Reputation: 29981
If your provider supports it, connection pooling handles this well enough in my experience. If you think it's a bottleneck you should of course benchmark.
In a similar line of thinking, I once created a class like this:
class Foo
{
SqlConnection con;
SqlCommand cmd1, cmd2;
void DoStuff();
static Foo GetFoo() { get from cache, or create a new one. }
}
Rather than construct a new one every request, I kept the connections open and commands ready for action, caching the entire Foo
object. This, disappointingly, was only very marginally more performant with SQL Server.
In your case there's the whole other layer of Entity Framework, so your overall improvement is going to be even less significant. In general I assume that if you're using EF you don't have a requirement for massive performance in the first place so the added complexity for such a small gain is probably not worth it.
Upvotes: 1