场景

Java性能优化-switch-case和if-else速度性能对比,到底谁快?:

Java性能优化-switch-case和if-else速度性能对比,到底谁快

如果单纯是做情景选择,建议使用switch,如果必须使用if-else,过多的if-else会让人看着很难受,

可以使用如下几个小技巧来简化过多的if-else。

注:

实现

使用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);

使用多态

优化前

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{
    @Override
    public Integer getType() {
        return 1;
    }
}

public class Age implements IType{
    @Override
    public Integer getType() {
        return 2;
    }
}

public class Address implements IType{
    @Override
    public Integer getType() {
        return 3;
    }
}

然后这样使用

IType itype = (IType)Class.forName("com.demo."+typeDesc).newInstance();
        Integer type1 = itype.getType();