Hi Team,

I think I have found a very small performance enhancement when using ResponseEntity.of

Currently the code for the method is

public static <T> ResponseEntity<T> of(Optional<T> body) {
    Assert.notNull(body, "Body must not be null");
    return body.map(ResponseEntity::ok).orElse(notFound().build());
}

That is the NOT_FOUND Response Entity is always built, even if it is not required.

The small change would be

public static <T> ResponseEntity<T> of(Optional<T> body) {
    Assert.notNull(body, "Body must not be null");
    return body.map(ResponseEntity::ok).orElseGet(() -> notFound().build());
}

By using the orElseGet method, the construction of the NOT_FOUND Response Entity is delayed until it is required.

There maybe other considerations here, such as the construction of the lambda needs to be balanced against the construction of the NOT_FOUND Response Entity.

In your estimation, is a PR worthwhile for this small enhancement?

Cheers, Brett

Comment From: jhoeller

Good point. I'll roll this into our upcoming 5.2.7 and 5.1.16 directly since we're about to wrap them up already. Thanks for offering to contribute a pull request, in any case, and thanks for raising this!