Skip to content

Commit 6de0be1

Browse files
ryanruppbclozel
authored andcommitted
Optimize initial buffer size in ContentCachingRequestWrapper
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
1 parent ed83461 commit 6de0be1

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

spring-web/src/main/java/org/springframework/web/util/ContentCachingRequestWrapper.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@
5656
*/
5757
public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
5858

59+
private static final int DEFAULT_BUFFER_SIZE = 1024;
60+
5961
private final ByteArrayOutputStream cachedContent;
6062

6163
@Nullable
@@ -75,7 +77,8 @@ public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
7577
public ContentCachingRequestWrapper(HttpServletRequest request) {
7678
super(request);
7779
int contentLength = request.getContentLength();
78-
this.cachedContent = new ByteArrayOutputStream(contentLength >= 0 ? contentLength : 1024);
80+
this.cachedContent = new ByteArrayOutputStream(contentLength >= 0 ?
81+
contentLength : DEFAULT_BUFFER_SIZE);
7982
this.contentCacheLimit = null;
8083
}
8184

@@ -88,7 +91,9 @@ public ContentCachingRequestWrapper(HttpServletRequest request) {
8891
*/
8992
public ContentCachingRequestWrapper(HttpServletRequest request, int contentCacheLimit) {
9093
super(request);
91-
this.cachedContent = new ByteArrayOutputStream(contentCacheLimit);
94+
int contentLength = request.getContentLength();
95+
int initialBufferSize = contentLength >= 0 ? contentLength : DEFAULT_BUFFER_SIZE;
96+
this.cachedContent = new ByteArrayOutputStream(Math.min(initialBufferSize, contentCacheLimit));
9297
this.contentCacheLimit = contentCacheLimit;
9398
}
9499

0 commit comments

Comments
 (0)