Entity Framework DbContext pooling performance benchmark

Although creating DbContext objects is really inexpensive, in really high performance scenarios it may be beneficial to switch to using Entity Frameworks DbContext pooling feature.

In this case EF Core will pool your context instances: when you dispose your context, EF Core resets its state and stores it in an internal pool; when a new instance is next requested, that pooled instance is returned instead of setting up a new one. Context pooling allows you to pay context setup costs only once at program startup.

There’s a simple benchmark on the Advanced Performance Topics page of the EF Core docs which I’ve adjusted slightly. It shows significant time and memory allocation savings when using DbContext pooling….

Click on the image for a larger view in a new tab…


Even though we are dealing with small times here in high volume apps the timing and reduced memory allocations can definitely make a difference.

Unfortunately there’s not a huge amount of documentation online about DbContext pooling. Arthur from the Entity Framework team gives a little more info on GitHub about how it works

If you want to turn on DbContext pooling in Entity Framework you can do so with or without Dependency Injection.

2 thoughts on “Entity Framework DbContext pooling performance benchmark”

  1. Hi Dave,

    Is there a way to define lifetime of the pooled contexts? Let’s say I don’t want the context to live more than an hour, so that I will have new contexts created every hour by calling DbContext constructor.

  2. The AsNoTracking method tells Entity Framework to stop that additional work and so, it can improve the performance of your application. So, in theory, a query with AsNoTracking should perform better than without.

Leave a Reply

Your email address will not be published.