Skip to content

Commit 0970b1d

Browse files
committed
Optimize ContentCachingRequestWrapper allocation
This commit builds on top of changes made in gh-29775 and gh-31737. Before this change, we would allocate several byte arrays even in cases of known request size. This could decrease performance when getting the cached content as it requires merging several arrays and data is not colocated in memory. This change ensures that we create a `FastByteArrayOutputStream` instance with the known request size so that the first allocated segment can contain the entire content. If the request size is not know, we will default back on the default allocation size for the `FastByteArrayOutputStream`. Closes gh-31834
1 parent a01c6d5 commit 0970b1d

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

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

+5-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@
5656
*/
5757
public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
5858

59-
private final FastByteArrayOutputStream cachedContent = new FastByteArrayOutputStream();
59+
private FastByteArrayOutputStream cachedContent;
6060

6161
@Nullable
6262
private final Integer contentCacheLimit;
@@ -74,6 +74,8 @@ public class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
7474
*/
7575
public ContentCachingRequestWrapper(HttpServletRequest request) {
7676
super(request);
77+
int contentLength = request.getContentLength();
78+
this.cachedContent = (contentLength > 0) ? new FastByteArrayOutputStream(contentLength) : new FastByteArrayOutputStream();
7779
this.contentCacheLimit = null;
7880
}
7981

@@ -86,6 +88,8 @@ public ContentCachingRequestWrapper(HttpServletRequest request) {
8688
*/
8789
public ContentCachingRequestWrapper(HttpServletRequest request, int contentCacheLimit) {
8890
super(request);
91+
int contentLength = request.getContentLength();
92+
this.cachedContent = (contentLength > 0) ? new FastByteArrayOutputStream(contentLength) : new FastByteArrayOutputStream();
8993
this.contentCacheLimit = contentCacheLimit;
9094
}
9195

0 commit comments

Comments
 (0)