Is there any difference between Objects::nonNull and x -> x != null?

£可爱£侵袭症+ 提交于 2019-11-29 03:49:19

As you noted, the semantics of the lambda x -> x != null and the method reference Objects::nonNull are virtually identical. I'm hard-pressed to think of any actual observable difference, short of digging into the class using reflection, or something like that.

There is a small space advantage to using the method reference over the lambda. With the lambda, the code of the lambda is compiled into a private static method of the containing class, and the lambda metafactory is then called with a reference to this static method. In the method reference case, the method already exists in the java.util.Objects class, so the lambda metafactory is call with a reference to the existing method. This results in a moderate space savings.

Consider these small classes:

class LM { // lambda
    static Predicate<Object> a = x -> x != null;
}

class MR { // method reference
    static Predicate<Object> a = Objects::nonNull;
}

(Interested readers should run javap -private -cp classes -c -v <class> to view detailed differences between the way these are compiled.)

This results in 1,094 bytes for the lambda case and 989 bytes for the method reference case. (Javac 1.8.0_11.) This isn't a huge difference, but if your programs are likely to have large numbers of lambdas like this, you might consider the space savings resulting from using method references.

In addition, it is more likely that a method reference could be JIT-compiled and inlined than the lambda, since the method reference is probably used a lot more. This might result in a tiny performance improvement. It seems unlikely this would make a practical difference, though.

Although you specifically said "Other than code style..." this really is mostly about style. These small methods were specifically added to the APIs so that programmers could use names instead of inline lambdas. This often improves the understandability of the code. Another point is that a method reference often has explicit type information that can help out in difficult type inference cases, such as nested Comparators. (This doesn't really apply to Objects::nonNull though.) Adding a cast or explicitly-typed lambda parameters adds a lot of clutter, so in these cases, method references are a clear win.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!