aspnetcore/performance/ObjectPool.md
By Günther Foidl, Steve Gordon, and Samson Amaugo
:::moniker range=">= aspnetcore-8.0"
xref:Microsoft.Extensions.ObjectPool is part of the ASP.NET Core infrastructure that supports keeping a group of objects in memory for reuse rather than allowing the objects to be garbage collected. All the static and instance methods in Microsoft.Extensions.ObjectPool are thread-safe.
Apps might want to use the object pool if the objects that are being managed are:
For example, the ASP.NET Core framework uses the object pool in some places to reuse xref:System.Text.StringBuilder instances. StringBuilder allocates and manages its own buffers to hold character data. ASP.NET Core regularly uses StringBuilder to implement features, and reusing them provides a performance benefit.
Object pooling doesn't always improve performance:
Use object pooling only after collecting performance data using realistic scenarios for your app or library.
NOTE: The ObjectPool doesn't place a limit on the number of objects that it allocates, it places a limit on the number of objects it retains.
When xref:Microsoft.Extensions.ObjectPool.DefaultObjectPoolProvider is used and T implements IDisposable:
NOTE: After the pool is disposed:
Get throws an ObjectDisposedException.Return disposes the given item.Important ObjectPool types and interfaces:
The ObjectPool can be used in an app in multiple ways:
ObjectPoolProvider<> in DI and using it as a factory.Call xref:Microsoft.Extensions.ObjectPool.ObjectPool`1.Get* to get an object and xref:Microsoft.Extensions.ObjectPool.ObjectPool`1.Return* to return the object. There's no requirement to return every object. If an object isn't returned, it will be garbage collected.
The following code:
ObjectPoolProvider to the Dependency injection (DI) container.IResettable interface to automatically clear the contents of the buffer when returned to the object pool.NOTE: When the pooled type T doesn't implement IResettable, then a custom PooledObjectPolicy<T> can be used to reset the state of the objects before they are returned to the pool.
:::moniker-end