0

I've been using java.util.Optional extensively in my code for better null handling. I even went as far as creating new "safe" datastructures with stuff like:

public Optional<Integer> indexOf(E elem) {...}

I'm curious to know if (not necessarily how much) this might impact my application's performance. Specifically, I have two main concerns:

  • Does the usage of java.util.Optional affect memory consumption or execution speed at all?
  • How does the JIT Compiler treat the Optional wrapping - is it efficient and throws out the wrapping and unwrapping, or could this conversion end up being a performance cost?

Any insights would be much appreciated.

xtay2
  • 453
  • 3
  • 14
  • It does affect things and is not magically optimized away. – Louis Wasserman Jun 11 '23 at 14:21
  • @LouisWasserman Do you know why? I have read other threads that talk about inlining of boxed/unboxed primitives/wrappers. It seems like a reasonable thing to do implement for Optional to. – xtay2 Jun 11 '23 at 14:26
  • `Optional` is meant to prevent you from making a [**billion** dollar mistake](https://youtu.be/YYkOWzrO3xg). I didn't come up with the dollar value. The guy who invented `null` did. – Elliott Frisch Jun 11 '23 at 15:33
  • 1
    Any optimization only affects your code when the optimizer actually applies it to your code. So there’s always an obvious difference to the code that doesn’t need this optimization in the first place. Will that difference be significant enough to bother you? That’s something we can’t tell. If the Java developers thought that there was no difference between `OptionalInt` and your `Optional`, they wouldn’t have added `OptionalInt` to the API. – Holger Jun 12 '23 at 09:20
  • 2
    Useful read: [GC overhead of Optional in Java](https://stackoverflow.com/q/54443944/2711488) – Holger Jul 24 '23 at 16:19

0 Answers0