Fundamentals 5 min read

Which Is Faster in Java: switch‑case or if‑else? A JMH Performance Comparison

Using JMH, the author benchmarks Java's switch‑case against if‑else and finds switch executes in about 0.44 ns per operation versus 1.55 ns for if‑else, with the gap widening as the number of branches increases.

The Dominant Programmer
The Dominant Programmer
The Dominant Programmer
Which Is Faster in Java: switch‑case or if‑else? A JMH Performance Comparison

Scenario

The article uses JMH (Java Microbenchmark Harness) to measure and compare the execution speed of switch‑case and if‑else statements in Java.

Implementation

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;

//if快还是switch快
//测试完成时间
@BenchmarkMode(Mode.AverageTime)
//设置统计结果的时间单位
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 2,time = 1,timeUnit = TimeUnit.SECONDS)
//测试次数和时间,参数同上
@Measurement(iterations = 5,time = 1,timeUnit = TimeUnit.SECONDS)
//fork一个线程,进行 fork 的次数,可用于类或者方法上。如果 fork 数是 2 的话,则 JMH 会 fork 出两个进程来进行测试。
@Fork(1)
//通过 State 可以指定一个对象的作用范围,JMH 根据 scope 来进行实例化和共享操作。@State 可以被继承使用,
//Scope.Thread:默认的 State,每个测试线程分配一个实例
@State(Scope.Thread)
public class SwitchVSIfTest {
    static Integer _NUM = 9;

    public static void main(String[] args) throws RunnerException {
        //启动基准测试
        Options options = new OptionsBuilder()
                .include(SwitchVSIfTest.class.getSimpleName())//要导入的测试类
                .build();
        new Runner(options).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;
        }
    }
}

Running the Benchmark

The benchmark is executed, and the raw JMH output shows:

//Benchmark                  Mode  Cnt  Score   Error  Units
//SwitchVSIfTest.ifTest      avgt    5  1.546 ± 0.288  ns/op
//SwitchVSIfTest.switchTest  avgt    5  0.443 ± 0.064  ns/op
Benchmark chart
Benchmark chart

Conclusion and Analysis

From the Score column, the average execution time of switch (0.443 ns) is noticeably lower than that of if‑else (1.546 ns). Bytecode inspection reveals that a switch loads the variable and performs a single comparison, whereas each if branch reloads the variable and evaluates the condition, leading to higher overhead.

When the number of branches increases, the performance advantage of switch becomes even more pronounced, confirming that switch scales better with many cases.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaPerformancebenchmarkif-elseJMHswitch-case
The Dominant Programmer
Written by

The Dominant Programmer

Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.