gpt4 book ai didi

java - 为什么单个 "if"比 "switch"慢?

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:44 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
What is the relative performance difference of if/else versus switch statement in Java?

给定以下两种方法:

public static int useSwitch(int i) {
switch (i) {
case 0:
return 1;
default:
return 0;
}
}

public static int useIf(int i) {
if (i == 0)
return 1;
return 0;
}

测试表明 switch 的执行速度比 if 版本稍快(在我的机器上每次调用 1.4 纳秒)。

我一直认为,只有在至少可以避免一些ifs 之前,转换的好处才会发挥作用,

为什么 switch 比单个 if 更快?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com