-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Fix] Avoid loading the response bodies twice in memory when parsing …
…`bytes.Buffer` (#984) ## Changes Prior to this PR, `WithResponseUnmarshal` was unmarshalling a response body to a `bytes.Buffer` by: 1. Reading all the response body in a slice of bytes; and 2. Writing that slice in the receiving `bytes.Buffer`. Step 1 unnecessarily increases the memory footprint as the response body is essentially stored twice in memory during unmarshalling. This PR fixes that problem by loading the body directly in the buffer without passing by an intermediate container. ## Tests Added a few unit test to cover all unmarshalling types. Memory benchmark: ```go var longString = strings.Repeat("a", 1<<30) func BenchmarkWithResponseUnmarshal_byteBuffer(b *testing.B) { b.ReportAllocs() client := NewApiClient(ClientConfig{ Transport: hc(func(r *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, Body: io.NopCloser(strings.NewReader(longString)), Request: r, }, nil }), }) for i := 0; i < b.N; i++ { var got bytes.Buffer client.Do(context.Background(), "GET", "/a", WithResponseUnmarshal(&got)) } } ``` Results: ``` Before: 6810268826 B/op 140 allocs/op After: 4294972868 B/op 101 allocs/op ``` - [x] `make test` passing - [x] `make fmt` applied - [x] relevant integration tests applied
- Loading branch information
1 parent
b55a992
commit b71c73d
Showing
2 changed files
with
116 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters