UrlResource computes a cleanedUrl in its constructor, but only uses it in a small number of methods (e.g. hashCode()). It has some String manipulations in it that can be expensive, so it might make sense to compute it lazily.
Some benchmarks (instantiate a FileUrlResource and check if it exists()):
class method median mean range
com.example.bench.ResourceBenchmark lazy 441889.554 460384.372 16671.778
com.example.bench.ResourceBenchmark default 415765.658 440910.870 18462.893
I think the fact that the median comparison is much more dramatic is probably because of garbage collection, which is quite noisy, and would be more common in the default case.
Spring Boot computes quite a few of these FileUrlResources on startup as it searches for application.properties files. The difference is just about noticeable (a few milliseconds on startup, and fewer GC failures).
Comment From: jhoeller
This turns out to be straightforward so that it can even be considered for 5.2.9.
One exception: UrlResource(String) needs the original input for the cleaned URL, so still builds it in the constructor where that original path is available. All the others, including the variants used by FileUrlResource, lazily resolve the cleaned URL now.
Comment From: dsyer
Great. In my tests I stored the original input in a field as well. That way it could always be lazy.
Comment From: jhoeller
Indeed, but at the expense of an additional field sticking around for any kind of UrlResource usage... I'd rather compute it early then. The plain String constructor is generally not efficient in that respect. If String computations are to be avoided, the input should always be a URL or URI or at least a decomposed protocol plus location part.