From 7f1062159ee9926d5abed7cadc2b36b6b7fc242e Mon Sep 17 00:00:00 2001 From: Arjen Poutsma Date: Thu, 22 Apr 2021 15:39:03 +0200 Subject: [PATCH] Copy HttpStatus::values to prevent allocation Before this commit, HttpStatus::resolve used the values() method in its logic. This causes a new array to be allocated for each invocation, and results in memory overhead. This commit makes a copy of the HttpStatus values array, and uses that to resolve status codes. Closes gh-26842 --- .../java/org/springframework/http/HttpStatus.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/HttpStatus.java b/spring-web/src/main/java/org/springframework/http/HttpStatus.java index 2153139007..5e995f5007 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpStatus.java +++ b/spring-web/src/main/java/org/springframework/http/HttpStatus.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -416,6 +416,13 @@ public enum HttpStatus { NETWORK_AUTHENTICATION_REQUIRED(511, Series.SERVER_ERROR, "Network Authentication Required"); + private static final HttpStatus[] VALUES; + + static { + VALUES = values(); + } + + private final int value; private final Series series; @@ -550,7 +557,8 @@ public enum HttpStatus { */ @Nullable public static HttpStatus resolve(int statusCode) { - for (HttpStatus status : values()) { + // used cached VALUES instead of values() to prevent array allocation + for (HttpStatus status : VALUES) { if (status.value == statusCode) { return status; }