java 高性能运算--switch 替代方案

本文探讨了Java中使用switch语句的性能问题,并提出了一种利用数组替代switch的优化方案,通过直接索引访问来提高执行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=small]
Java 原生的语法糖中存在很多种 易于阅读,效率略低的方案,我们可以适当改写。

比如 switch 语法糖。

[/size]


int re = 0;
for(int i=0;i<10000000;i++){
re = switch(i);
}

protected int switch(int z){
int i = z%10+1;
switch(i){
case 1: return 3;
case 2:return 6;
case 3:return 7;
case 4:return 8;
case 5:return 10;
case 6:return 16;
case 7:return 18;
case 8:return 20;
default:return -1;
}
}


switch 本身的性能并不差,但是仍存在可以提高的空间,尤其在随机次数比较大的高频调用中。

我们可以换一种思路,来取得比较可观的效果。


int re = 0;
int [] sw = new int[]{3,6,7,8,10,16,18,20};
for(int i=0;i<100000000;i++){
re = arrayInt(sw,i);
}

protected int arrayInt(int []sw,int z){
int i = z%10+1;

if(i>7 || i<1){
return -1;// 缺省值
}else{
return sw[i];
}
}


这种思路 相比与switch 分支判断来说,效率有所提升,因为对数据的随机访问是非常快的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

annan211

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值