Skip to content

Commit

Permalink
Copy HttpStatus::values to prevent allocation
Browse files Browse the repository at this point in the history
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
  • Loading branch information
poutsma committed Apr 22, 2021
1 parent e4c0ff5 commit 7f10621
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions 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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -550,7 +557,8 @@ public static HttpStatus valueOf(int statusCode) {
*/
@Nullable
public static HttpStatus resolve(int statusCode) {
for (HttpStatus status : values()) {
// used cached VALUES instead of values() to prevent array allocation

This comment has been minimized.

Copy link
@PascalSchumacher

PascalSchumacher May 12, 2021

Contributor

I guess this should be use instead of used?

This comment has been minimized.

Copy link
@sbrannen

sbrannen May 13, 2021

Member

Indeed. I'll make the change on main.

for (HttpStatus status : VALUES) {
if (status.value == statusCode) {
return status;
}
Expand Down

0 comments on commit 7f10621

Please sign in to comment.