Java的性能可选 [英] Performance of Java Optional
问题描述
我在Java 8中偶然发现了Optional类 - 我真的很喜欢在我的代码中使用isPresent()方法调用替换一些空检查(字面意思是值是否存在?)的方法。
I just stumbled upon the Optional class in Java 8 - I really like the approach of replacing some of the null checks (which literally means "is the value present?") in my code with isPresent() method calls.
我的问题是:这不会导致我的代码性能下降吗?我只是猜测简单的空检查可能会有点便宜,而且我在字节码读取/解释方面还不是很好,所以我对你对这个主题的想法非常感兴趣。
My question is: Wouldn't that cause a lower performance of my code? I am just guessing simple null checks could be a bit cheaper and I am not yet very good in byte code reading / interpretation, so I am really interested in your thoughts on that topic.
推荐答案
可选< T>
只是一个普通的泛型类,它包含类型为T的引用。因此,它添加了一个间接层。方法调用本身也不会非常昂贵,因为类是 final
,因此可以避免动态调度。
Optional<T>
is just a normal generic class which contains a reference of type T. Thus, it adds a single layer of indirection. The method calls themselves won't be very expensive either, since the class is final
and so the dynamic dispatch can be avoided.
唯一可能遇到性能问题的地方是使用大量此类实例,但即便如此,之类的性能也是如此Stream< Optional< String>>
一点都不差。但是,在处理大量原始值时,您会发现使用 Stream< Integer>
(或 Integer []
)与原始专业化 IntStream
(或 int []
)由于这个间接层需要非常经常实例化 Integer
对象。但是,这是我们已经知道并且在使用 ArrayList< Integer>
等内容时付出的代价。
The only place where you could have performance problems is when working with very large numbers of such instances, but even then the performance of something like a Stream<Optional<String>>
is not bad at all. However, when working with large amounts of primitive values, you'll find a performance hit using Stream<Integer>
(or Integer[]
) versus the primitive specialization IntStream
(or int[]
) due to this layer of indirection requiring very frequent instantiation of Integer
objects. However, this is a penalty that we already know and do pay when using things like ArrayList<Integer>
.
您显然会遇到 Stream< OptionalInt>
/ OptionalInt []
,因为OptionalInt基本上是一个类使用 int
字段和布尔
表示状态(与可选< T> <不同/ code>只能与
T
字段一起使用,因此非常类似于整数
虽然更大在尺寸方面。当然, Stream< Optional< Integer>>
会添加两个级别的间接,并带来相应的双重性能损失。
You would obviously experience the same hit with Stream<OptionalInt>
/ OptionalInt[]
, since an OptionalInt is basically a class with an int
field and a boolean
flag for presence (unlike with Optional<T>
which can make do with only the T
field) and thus quite similar to Integer
although bigger in size. And of course, a Stream<Optional<Integer>>
would add two levels of indirection, with the corresponding double performance penalty.
这篇关于Java的性能可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!