The closest similar question and answer I could find was: GC overhead of Optional<T> in Java which basically says: This is fine. Only, maybe, convincingly.
But it doesn't go into comparing to a case where you have a very easy and just as readable option to not use the Optional
. In such a case isn't there utility in avoiding the use of some more memory?
Basically say I have a frequently accessed class containing a map (populated from JSON or whatever is going on) and it's like:
public class Info() {
private static final String DEFAULT_USER = "guest";
private final Map<String, String> info; // initialized in constructor
...
public String getUser_exhibitA() {
return Optional.ofNullable(info.get("user")).orElse(DEFAULT_USER);
}
...
public String getUser_exhibitB() {
return info.getOrDefault("user", DEFAULT_USER);
}
...
}
And say calling getUser is a frequent call all over the application.
Assuming that there's never an info.put("user", null)
then either getUser
exhibit behaves the same — except for allocating an Optional
or not.
Maybe it hardly matters (as per the linked question) but it seems to me exhibitB is preferable and avoids the one-shot Optional
allocation per get.
Am I missing on some optimization specific to frequently used and discarded classes like Optional
E.G. is there maybe a permanent bank of Optional that actually get reused for this? Shouldn't the exhibitB approach be generally recommended over exhibitA?