可选vs if/else-if性能Java 8 [英] Optional vs if/else-if performance java 8
问题描述
你好,我有两个代码示例
Hello i have two samples of code
if/else if/else语句
if/else if/else statements
private Object getObj(message) {
if (message.getA() != null)
return message.getA();
else if (message.getB() != null)
return message.getB();
else if (message.getC() != null)
return message.getC();
else return null;
}
可选语句
private Optional<Object> wrap(Object o){
return Optional.ofNullable(o);
}
private Object getObj(message) {
return wrap(message.getA())
.orElseGet(() -> wrap(message.getB())
.orElseGet(() -> wrap(message.getC())
.orElse(null)));
}
所以我的问题是,这两者在性能方面如何比较(我在实际代码中大约有15-20条if-else语句)?
So my question is how these two compare in terms of performance (i have about 15-20 if-else statements on actual code)?
值得重构代码的可读性与性能,还是滥用可选选项?
Is it worth refactoring the code readability vs performance or is a misusage of optionals?
在if/else-if语句增长到100+的情况下,性能损失又是多少?
Also what is the performance penalty in case the if/else-if statements grown to 100+?
预先感谢
推荐答案
不要将Optional
用于条件逻辑.
Don't use Optional
s for conditional logic.
它们被设计为 从一种方法中返回以表明可能不存在的值 .
They were designed, to be returned from a method to indicate a potentially absent value.
仅仅因为您可以将它们很好地链接成一行并不意味着它是可以理解的.您实际上也一无所获. 性能开销可能很大.在最坏的情况下,将创建N
对象,然后将其丢弃.只需留在您的普通" if-else
链上即可.
Just because you can nicely chain them into a single line doesn't mean that it's understandable. Also you literally gain nothing. The performance overhead may be significant. In the worst case N
objects being created and then discarded. Just stay with your "normal" if-else
chains.
不要寻找使您的当前代码更具可读性的方法,而是退后一步,问问自己为什么您需要15到20条if-else语句.你能分解一些逻辑吗?为什么为什么首先需要为具有多个可能具有不同类型的许多不同字段提供一个吸气剂?等等
Instead of finding ways to make your current code more readable, take a step back and ask yourself why you need 15-20 if-else statements. Can you split some logic up? Why do you need a getter for so many different fields with potentially different types in the first place? etc.
这篇关于可选vs if/else-if性能Java 8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!