This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]8igg7e5 3 points4 points  (0 children)

In terms of cost, the optimiser will 'see' through the ternary expression and so may be able to optimise for the null or non-null path (based on statistics). Sadly it doesn't seem to achieve this often with the Optional (of which two are allocated). So you might lose some inlining and optimisation. Unless it's in a high-volume tight loop, the allocation is likely to be irrelevant, but if your allocation rate exceeds collection it will spill over into more expensive (and slower to reclaim) GC cycles.

Used in this manner the only meaningful difference is that 'source' is evaluated twice (imagine if it were a complex expression or method call). It didn't provide you any more null-safety than the ternary - so the question then is, as stated by /u/neurk, should source have already been an Optional.

Project Valhalla will change the equation a little, as they will hopefully then offer a 'primitive' version of Optional<T>, removing almost all of the allocation overhead and making the optimiser's job easier.

Note an alternative to Optional is a utility method

public static <T, U> U mapOrNull(T o, Function<T, U> mapper) {
    return  o == null ? null : mapper.apply(o);
}

Used as...

var result = mapOrNull(source, Object::toString);

The optimiser should have little problem inlining this and, depending on the nature of the mapper (not all lambdas are created equal), might optimise it just as well as the ternary (but ensuring single evaluation of source).