原理性分析Switch和If的执行效率,理解阿里代码规约


作者:樊远航

文章推荐理由

从性能测试开始,引出文章主题,通过字节码分析两者性能差别原理,并对switch自身策略不同引起性能不同做了分析,文章分析逻辑清晰,并加上了自身的实践

条件判断语句是程序的重要组成部分,也是系统业务逻辑的控制手段。重要程度和使用频率更是首屈一指,那我们要如何选择 if 还是 switch 呢?他们的性能差别有多大?switch 性能背后的秘密是什么?接下来让我们一起来寻找这些问题的答案。

测试代码

我们采用Oracle提供的JMH(JAVA微基准测试套件)框架来测试,首先引入相关依赖,在pom中添加如下:

<!-- https://mvnrepository.com/artifact/org.openjdk.jmh/jmh-core -->
<dependency>
    <groupId>org.openjdk.jmh</groupId>
    <artifactId>jmh-core</artifactId>
    <version>1.23</version>
</dependency>
<dependency>
    <groupId>org.openjdk.jmh</groupId>
    <artifactId>jmh-generator-annprocess</artifactId>
    <version>1.20</version>
    <scope>provided</scope>
</dependency>

然后编写测试代码:switch、if分别五个分支执行对比。

package com.example.demo.test;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
/**
* 测试代码
*
* @author fanyuanhang
* @date 2020年05月12日 15:29:09
*/
@BenchmarkMode(Mode.AverageTime) // 测试完成时间
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS) // 预热 2 轮,每次 1s
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) // 测试 5 轮,每次 3s
@Fork(1) // fork 1 个线程
@State(Scope.Thread) // 每个测试线程一个实例
public class SwitchOptimizeTest {
    static Integer _NUM = 9;
    public static void main(String[] args) throws RunnerException {
        // 启动基准测试
        Options opt = new OptionsBuilder()
                .include(SwitchOptimizeTest.class.getSimpleName()) // 要导入的测试类
                .output("/Users/fanyuanhang/Downloads/jmh-switch.log") // 输出测试结果的文件
                .build();
        new Runner(opt).run(); // 执行测试
    }
    @Benchmark
    public void switchTest() {
        int num1;
        switch (_NUM) {
            case 1:
                num1 = 1;
                break;
            case 3:
                num1 = 3;
                break;
            case 5:
                num1 = 5;
                break;
            case 7:
                num1 = 7;
                break;
            case 9:
                num1 = 9;
                break;
            default:
                num1 = -1;
                break;
        }
    }
    @Benchmark
    public void ifTest() {
        int num1;
        if (_NUM == 1) {
            num1 = 1;
        } else if (_NUM == 3) {
            num1 = 3;
        } else if (_NUM == 5) {
            num1 = 5;
        } else if (_NUM == 7) {
            num1 = 7;
        } else if (_NUM == 9) {
            num1 = 9;
        } else {
            num1 = -1;
        }
    }
}

测试结果:
在这里插入图片描述
我们发现,switch的执行效率是if的大概2.33倍。
加大难度,我们执行15个分支(因为代码一样,所以此处代码略),我们发现15个分支的时候,性能差异居然到了接近5倍!

性能分析

那么是什么原因导致的switch和if的性能差异这么大呢?查阅资料后我发现是因为它们的字节码的问题。那么我们来看一看它们的字节码文件吧:

public class com.example.optimize.SwitchOptimize {
static java.lang.Integer _NUM;
public com.example.optimize.SwitchOptimize();
        Code:
        0: aload_0
        1: invokespecial #1                  // Method java/lang/Object."<init>":()V
        4: return
public static void main(java.lang.String[]);
        Code:
        0: invokestatic  #7                  // Method switchTest:()V
        3: invokestatic  #12                 // Method ifTest:()V
        6: return
public static void switchTest();
        Code:
        0: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        3: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        6: tableswitch   { // 1 to 9
        1: 56
        2: 83
        3: 61
        4: 83
        5: 66
        6: 83
        7: 71
        8: 83
        9: 77
default: 83
        }
        56: iconst_1
        57: istore_0
        58: goto          85
        61: iconst_3
        62: istore_0
        63: goto          85
        66: iconst_5
        67: istore_0
        68: goto          85
        71: bipush        7
        73: istore_0
        74: goto          85
        77: bipush        9
        79: istore_0
        80: goto          85
        83: iconst_m1
        84: istore_0
        85: return
public static void ifTest();
        Code:
        0: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        3: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        6: iconst_1
        7: if_icmpne     15
        10: iconst_1
        11: istore_0
        12: goto          81
        15: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        18: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        21: iconst_3
        22: if_icmpne     30
        25: iconst_3
        26: istore_0
        27: goto          81
        30: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        33: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        36: iconst_5
        37: if_icmpne     45
        40: iconst_5
        41: istore_0
        42: goto          81
        45: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        48: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        51: bipush        7
        53: if_icmpne     62
        56: bipush        7
        58: istore_0
        59: goto          81
        62: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        65: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        68: bipush        9
        70: if_icmpne     79
        73: bipush        9
        75: istore_0
        76: goto          81
        79: iconst_m1
        80: istore_0
        81: return
static {};
        Code:
        0: iconst_1
        1: invokestatic  #25                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
        4: putstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        7: return
        }

这些字节码中最重要的信息是这一行: getstatic #15
这段代表代码取出_NUM变量和条件进行判断。
从上面的字节码可以看出,在switch中只取出了一次变量和条件进行判断;而if中,每进行一次判断都要重新去获取变量再判断,所以正是因为这种重复性的动作导致了if效率要比switch低很多。
而且,随着分支的增加,效率的差异会越来越大,这也就是为什么阿里巴巴代码规约中明确要求:if分支中不要多层嵌套if-else分支,因为这样会导致冗余复杂的if-else分支使得代码运行效率低下。

Switch自身的策略

对于 switch 来说,他最终生成的字节码有两种形态,一种是 tableswitch,另一种是 lookupswitch,决定最终生成的代码使用那种形态取决于 switch 的判断添加是否紧凑,例如到 case 是 1…2…3…4 这种依次递增的判断条件时,使用的是 tableswitch,而像 case 是 1…33…55…22 这种非紧凑型的判断条件时则会使用 lookupswitch,测试代码如下:

public class SwitchOptimize {
    static Integer _NUM = 1;
    public static void main(String[] args) {
        tableSwitchTest();
        lookupSwitchTest();
    }
    public static void tableSwitchTest() {
        int num1;
        switch (_NUM) {
            case 1:
                num1 = 1;
                break;
            case 2:
                num1 = 2;
                break;
            case 3:
                num1 = 3;
                break;
            case 4:
                num1 = 4;
                break;
            case 5:
                num1 = 5;
                break;
            case 6:
                num1 = 6;
                break;
            case 7:
                num1 = 7;
                break;
            case 8:
                num1 = 8;
                break;
            case 9:
                num1 = 9;
                break;
            default:
                num1 = -1;
                break;
        }
    }
    public static void lookupSwitchTest() {
        int num1;
        switch (_NUM) {
            case 1:
                num1 = 1;
                break;
            case 11:
                num1 = 2;
                break;
            case 3:
                num1 = 3;
                break;
            case 4:
                num1 = 4;
                break;
            case 19:
                num1 = 5;
                break;
            case 6:
                num1 = 6;
                break;
            case 33:
                num1 = 7;
                break;
            case 8:
                num1 = 8;
                break;
            case 999:
                num1 = 9;
                break;
            default:
                num1 = -1;
                break;
        }
    }
}

字节码如下:

public class com.example.optimize.SwitchOptimize {
static java.lang.Integer _NUM;
public com.example.optimize.SwitchOptimize();
        Code:
        0: aload_0
        1: invokespecial #1                  // Method java/lang/Object."<init>":()V
        4: return
public static void main(java.lang.String[]);
        Code:
        0: invokestatic  #7                  // Method tableSwitchTest:()V
        3: invokestatic  #12                 // Method lookupSwitchTest:()V
        6: return
public static void tableSwitchTest();
        Code:
        0: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        3: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        6: tableswitch   { // 1 to 9
        1: 56
        2: 61
        3: 66
        4: 71
        5: 76
        6: 81
        7: 87
        8: 93
        9: 99
default: 105
        }
        56: iconst_1
        57: istore_0
        58: goto          107
        61: iconst_2
        62: istore_0
        63: goto          107
        66: iconst_3
        67: istore_0
        68: goto          107
        71: iconst_4
        72: istore_0
        73: goto          107
        76: iconst_5
        77: istore_0
        78: goto          107
        81: bipush        6
        83: istore_0
        84: goto          107
        87: bipush        7
        89: istore_0
        90: goto          107
        93: bipush        8
        95: istore_0
        96: goto          107
        99: bipush        9
        101: istore_0
        102: goto          107
        105: iconst_m1
        106: istore_0
        107: return
public static void lookupSwitchTest();
        Code:
        0: getstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        3: invokevirtual #19                 // Method java/lang/Integer.intValue:()I
        6: lookupswitch  { // 9
        1: 88
        3: 98
        4: 103
        6: 113
        8: 125
        11: 93
        19: 108
        33: 119
        999: 131
default: 137
        }
        88: iconst_1
        89: istore_0
        90: goto          139
        93: iconst_2
        94: istore_0
        95: goto          139
        98: iconst_3
        99: istore_0
        100: goto          139
        103: iconst_4
        104: istore_0
        105: goto          139
        108: iconst_5
        109: istore_0
        110: goto          139
        113: bipush        6
        115: istore_0
        116: goto          139
        119: bipush        7
        121: istore_0
        122: goto          139
        125: bipush        8
        127: istore_0
        128: goto          139
        131: bipush        9
        133: istore_0
        134: goto          139
        137: iconst_m1
        138: istore_0
        139: return
static {};
        Code:
        0: iconst_1
        1: invokestatic  #25                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
        4: putstatic     #15                 // Field _NUM:Ljava/lang/Integer;
        7: return
        }

从上面字节码可以看出 tableSwitchTest 使用的 tableswitch,而 lookupSwitchTest 则是使用的 lookupswitch。
分析:
当执行一次 tableswitch 时,堆栈顶部的 int 值直接用作表中的索引,以便抓取跳转目标并立即执行跳转。也就是说 tableswitch 的存储结构类似于数组,是直接用索引获取元素的,所以整个查询的时间复杂度是 O(1),这也意味着它的搜索速度非常快。
而执行 lookupswitch 时,会逐个进行分支比较或者使用二分法进行查询,因此查询时间复杂度是 O(log n),所以使用 lookupswitch 会比 tableswitch 慢。测试:

同样的代码,我们对比下lookupswitch和tableswitch的效率:

package com.example.optimize;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.concurrent.TimeUnit;
@BenchmarkMode(Mode.AverageTime) // 测试完成时间
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2, time = 1, timeUnit = TimeUnit.SECONDS) // 预热 2 轮,每次 1s
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) // 测试 5 轮,每次 3s
@Fork(1) // fork 1 个线程
@State(Scope.Thread) // 每个测试线程一个实例
public class SwitchOptimizeTest {
    static Integer _NUM = -1;
    public static void main(String[] args) throws RunnerException {
        // 启动基准测试
        Options opt = new OptionsBuilder()
                .include(SwitchOptimizeTest.class.getSimpleName()) // 要导入的测试类
                .build();
        new Runner(opt).run(); // 执行测试
    }
    @Benchmark
    public void tableSwitchTest() {
        int num1;
        switch (_NUM) {
            case 1:
                num1 = 1;
                break;
            case 2:
                num1 = 2;
                break;
            case 3:
                num1 = 3;
                break;
            case 4:
                num1 = 4;
                break;
            case 5:
                num1 = 5;
                break;
            case 6:
                num1 = 6;
                break;
            case 7:
                num1 = 7;
                break;
            case 8:
                num1 = 8;
                break;
            case 9:
                num1 = 9;
                break;
            default:
                num1 = -1;
                break;
        }
    }
    @Benchmark
    public void lookupSwitchTest() {
        int num1;
        switch (_NUM) {
            case 1:
                num1 = 1;
                break;
            case 11:
                num1 = 2;
                break;
            case 3:
                num1 = 3;
                break;
            case 4:
                num1 = 4;
                break;
            case 19:
                num1 = 5;
                break;
            case 6:
                num1 = 6;
                break;
            case 33:
                num1 = 7;
                break;
            case 8:
                num1 = 8;
                break;
            case 999:
                num1 = 9;
                break;
            default:
                num1 = -1;
                break;
        }
    }
}

在这里插入图片描述
可以看出在分支判断为 9 个时,tableswitch 的性能比 lookupwitch 的性能快了约 1.3 倍。但即使这样 lookupwitch 依然比 if 查询性能要高很多。

总结

switch 的判断条件是 5 个时,性能比 if 高出了约 2.3 倍,而当判断条件的数量越多时,他们的性能相差就越大。而 switch 在编译为字节码时,会根据 switch 的判断条件是否紧凑生成两种代码:tableswitch(紧凑时生成)和 lookupswitch(非紧凑时生成),其中 tableswitch 是采用类似于数组的存储结构,直接根据索引查询元素;而 lookupswitch 则需要逐个查询或者使用二分法查询,因此 tableswitch 的性能会比 lookupswitch 的性能高,但无论如何 switch 的性能都比 if 的性能要高。

猜你喜欢

转载自blog.csdn.net/runlion_123/article/details/107006769