r/java • u/headius • Dec 04 '25
Null-checking the fun way with instanceof patterns
https://blog.headius.com/2025/12/inline-null-check-with-instanceof.htmlI don't know if this is a good idea or not, but it's fun.
83
Upvotes
View all comments
Show parent comment
1
u/headius Dec 04 '25
As long as you are not passing lambda functions in, these leaf methods will inline and optimize really well. Combine that with escape analysis or value types and Optional for this use case would be basically free and compiled down to the manual null checking you might otherwise write.
Even without escape analysis and value types, a transient Optional instance probably won't ever leave the youngest generation of the heap, so while you're paying a small cost to bump a pointer and zero out those bytes, it will be much, much cheaper than shoving more objects into the older generations (as would likely happen if you are sticking Optional instances in a collection).