Early out in ObjectPool to avoid loop execution #1985
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This is a micro optimization which caught my eye when profiling my own application. I haven't tested the impact on overall execution performance. But given that the pool is used at basically every function invocation, I assume that it won't hurt to change it. Given that the change doesn't make the code much harder to understand or maintain, I just did it.
Motivation
The object pool is only used internally and a few of them are allocated per
Engine
instance. The pool has basically "best effort" guarantees. Given thatEngine
itself is not declared as thread safe, no synchronization was used for the change.The performance problem was mainly with empty or almost empty pools. In those cases, the pool always looped over its internal array to find a possible match. Given that the pool can easily track how many items are currently stored within the array, an early out mechanism was added.
Benchmark
Here are the results. The benchmark code is attached below.
GetFromEmpty:
GetFromFilledWithOne:
GetFromAlmostFull:
GetFromFullyFilled:
Benchmark Code
The benchmark always fetches 12 items from the pool. The overhead of allocating and
filling the pool is not relevant because the same code is used for both, before and after.