dotnet / EntityFramework.Docs

Documentation for Entity Framework Core and Entity Framework 6
https://docs.microsoft.com/ef/
Creative Commons Attribution 4.0 International
1.63k stars 1.96k forks source link

Push people more aggressively towards context pooling #3825

Open roji opened 2 years ago

roji commented 2 years ago

Our unpooled DbContext instantiation has become heavy enough that using pooling is a really idea in the real world, not just in high-perf TechEmpower-like scenarios. The benchmark in https://github.com/dotnet/efcore/issues/27694#issuecomment-1086817667 does a simple non-tracking query which retrieves a simple empty row:

Method Rows Mean Error StdDev Median
EFCore 1 974.1 us 44.82 us 131.46 us 960.2 us
EFCorePooled 1 479.4 us 31.75 us 93.11 us 444.4 us

That's half a millisecond of absolute time spent setting up various services in memory, or a 50% improvement in relative terms (note these results are against localhost, so the gap would be less significant as the database is farther away). This again makes EF Core slow out-of-the-box, requiring extra knobs and knowledge to make it perform well, and the discoverability of context pooling isn't great.

We could add an analyzer which identifies non-pooled APIs and warns, guiding people towards the pooling APIs instead. For example, ServiceCollection.AddDbContext would cause a warning, pointing towards AddPooledDbContext. For non-DI use, we could identify constructors on the user's DbContext-inherited type (which call the base constructor), and flag on them.

AraHaan commented 2 years ago

What about those who use ServiceCollection.AddSqlServer(connectionString)?

for an analyzer that scans for polled connections, perhaps it should mark that to use an overload that makes pooled ones.

roji commented 2 years ago

Team decision: we won't be adding any analyzers around this at this point, but we will try to guide people via documentation to use context pool whenever their scenario permits it.