0

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?

dlamblin
  • 43,965
  • 20
  • 101
  • 140
  • 3
    Yes, getOrDefault() is preferrable. First because it's much simpler and clearer. Second because Optional is not designed to replace null checks. It's designed to be used as a return type of a method that can return "empty" values, to make it obvious that the "empty" case can happen. Performance is irrelevant. – JB Nizet Aug 23 '19 at 19:30
  • Code should be readable. Say what you mean. So getOrDefault() is preferrable. – Jonathan Rosenne Aug 24 '19 at 05:13

0 Answers0