if->return vs. if->else efficiency

后端 未结 6 1191
一整个雨季
一整个雨季 2020-12-28 12:35

This may sound like a silly question, and I hesitated to post it, but still: if something needs to run only in a certain condition, which of these is more efficient:

6条回答
  •  眼角桃花
    2020-12-28 13:08

    It's a style thing. The performance is not relevant; both produce nearly identical machine code.

    A few considerations on the style:

    If you want to avoid 'horizontal programming', you might want to prefer B to avoid nested conditions. For example, if you want to add exceptions without affecting the flow of the method too much:

    A:

    public String getDescription(MyObject obj) {
        if (obj == null) {
            return "";
        } else {
            if (!obj.isValid()) {
                return "invalid";
            } else {
                ...
            }
        }
     }
    

    B:

    public String getDescription(MyObject obj) {
        if (obj == null) {
            return "";
        }
    
        if (!obj.isValid()) {
            return "invalid";
        }
    
        ....
     }
    

    But the difference is minimal if you ask me. Definitely not worth a 'code style war'.

提交回复
热议问题