場景
Java性能優化-switch-case和if-else速度性能對比,到底誰快?:
Java性能優化-switch-case和if-else速度性能對比,到底誰快?-CSDN博客
如果單純是做情景選擇,建議使用switch,如果必須使用if-else,過多的if-else會讓人看著很難受,
可以使用如下幾個小技巧來簡化過多的if-else。
注:
博客:
霸道流氓氣質-CSDN博客
實現
使用return去掉多余的else
優化前
??????? String a = "badao";if("badao".equals(a)){//業務代碼}else{return;}
優化后
??????? if(!"badao".equals(a)){return;}
用Map數組把相關的判斷信息定義為元素信息
優化前
??????? int type = 2;String typeName = "default";if(type ==1){typeName = "name1";}else if(type==2){typeName = "name2";}else if(type ==3){typeName = "name3";}
優化后
??????? Map<Integer,String> typeMap = new HashMap<>();typeMap.put(1,"name1");typeMap.put(2,"name2");typeMap.put(3,"name3");typeName = typeMap.get(type);
使用三元運算符
優化前
??????? Integer score = 82;String aa;if(score>80){aa = "A";}else{aa = "B";}
優化后
aa = score>80?"A":"B";
合并條件表達式
優化前
??????? String name = "badao";String city = "qingdao";if("qingdao".equals(city)){//執行業務邏輯1}if("badao".equals(name)){//執行業務邏輯1}
優化后
??????? if("qingdao".equals(city) || "badao".equals(name)){//執行業務邏輯1}
使用枚舉
優化前
??????? Integer typeId = 0;String typeDesc = "Name";if("Name".equals(typeDesc)){typeId = 1;}else if("Address".equals(typeName)){typeId = 2;}else if("Age".equals(typeName)){typeId = 3;}
優化后
先定義一個枚舉
??? public enum TypeEnum{Name(1),Age(2),Address(3);public Integer typeId;TypeEnum(Integer typeId){this.typeId = typeId;}}
然后這樣使用
Integer typeId1 = TypeEnum.valueOf("Name").typeId;
使用Optional省略非空判斷
優化前
??????? String str = "badao";if(str!=null){System.out.println(str);}
優化后
??????? Optional<String> str1 = Optional.ofNullable(str);str1.ifPresent(System.out::println);
更多請參考
Java8中Optional類入門-替代null避免冗雜的非空校驗_optional<object>-CSDN博客
使用多態
優化前
??????? Integer typeId = 0;String typeDesc = "Name";if("Name".equals(typeDesc)){typeId = 1;}else if("Address".equals(typeName)){typeId = 2;}else if("Age".equals(typeName)){typeId = 3;}
優化后
新建接口類
public interface IType {Integer getType();
}
分別新建三個實現類
public class Name implements IType{@Overridepublic Integer getType() {return 1;}
}public class Age implements IType{@Overridepublic Integer getType() {return 2;}
}public class Address implements IType{@Overridepublic Integer getType() {return 3;}
}
然后這樣使用
??????? IType itype = (IType)Class.forName("com.demo."+typeDesc).newInstance();Integer type1 = itype.getType();