Skip to content

Commit

Permalink
Optimize initial buffer size in ContentCachingRequestWrapper
Browse files Browse the repository at this point in the history
Prior to this commit, the initial buffer size for content caching
allocated in `ContentCachingRequestWrapper` would be:

* the request content length, if available in request headers
* the cache limit size as configured on the wrapper

The latter is really an upper bound and should not be considered as a
good default in most cases. This commit ensures that the request content
length is still used if available, but uses a default 1024 size if it's
not.

While this change will probably cause more reallocations as the buffer
grows, this will avoid large allocations in many cases and should
overall help with GC.

Closes gh-29775
  • Loading branch information
ryanrupp authored and bclozel committed Sep 11, 2023
1 parent ed83461 commit 6de0be1
Showing 1 changed file with 7 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
*/
public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {

private static final int DEFAULT_BUFFER_SIZE = 1024;

private final ByteArrayOutputStream cachedContent;

@Nullable
Expand All @@ -75,7 +77,8 @@ public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
public ContentCachingRequestWrapper(HttpServletRequest request) {
super(request);
int contentLength = request.getContentLength();
this.cachedContent = new ByteArrayOutputStream(contentLength >= 0 ? contentLength : 1024);
this.cachedContent = new ByteArrayOutputStream(contentLength >= 0 ?
contentLength : DEFAULT_BUFFER_SIZE);
this.contentCacheLimit = null;
}

Expand All @@ -88,7 +91,9 @@ public ContentCachingRequestWrapper(HttpServletRequest request) {
*/
public ContentCachingRequestWrapper(HttpServletRequest request, int contentCacheLimit) {
super(request);
this.cachedContent = new ByteArrayOutputStream(contentCacheLimit);
int contentLength = request.getContentLength();
int initialBufferSize = contentLength >= 0 ? contentLength : DEFAULT_BUFFER_SIZE;
this.cachedContent = new ByteArrayOutputStream(Math.min(initialBufferSize, contentCacheLimit));
this.contentCacheLimit = contentCacheLimit;
}

Expand Down

0 comments on commit 6de0be1

Please sign in to comment.