Optional vs if/else-if performance java 8

前端 未结 5 1787
我寻月下人不归
我寻月下人不归 2021-02-19 22:58

Hello i have two samples of code

if/else if/else statements

private Object getObj(message) {
        if (message         


        
5条回答
  •  清歌不尽
    2021-02-19 23:52

    Don't use Optionals for conditional logic.

    They were designed, to be returned from a method to indicate a potentially absent value.

    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.


    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.

提交回复
热议问题