Decrease allocations in encode loop. #86
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.
Motivation
While investigating performance of HTTP/2 I noticed a substantial number
of allocations occuring in a hot loop in header compression. Specifically
I set up a simple harness that encoded headers 100 times, and then ran
that harness 10k times. This harness ended up performing 17 million
allocations, which is frankly a bit too high!
The fact that the number of allocations was in the millions suggested that
we were allocating some resources per header encode. That's not good:
assuming the target
ByteBuffer
is big enough we should not need toperform new allocations to encode headers.
The allocations came from two places. Firstly, we were allocating in the
HeaderTableStorage.indices(matching:)
function. This was because thatoperation was returning a lazy collection, which required multiple heap
allocations for the closure contexts. Those needed to be eliminated.
Secondly, we were triggering a CoW of the
ByteBuffer
passed in toencode()
. This is the result of a complex bit of control flow thatfundamentally meant that the buffer was held in two places in that
method.
Removing these two sources of allocations dropped the count in my test
from 17 million to 176k, a decrease of 100x. We also saw a speed boost
of nearly 66% in terms of runtime of the microbenchmark.
Modifications
HeaderTableStorage.indices(matching:)
the repeated logic of the body of the two loops over the header
indices.
cause a CoW operation.
Result
Much faster and more memory efficient header encoding.