Java 代码优化之 for 循环

127 阅读1分钟

常言道:细节决定成败。

在开发过程中,很容易忽略一些细小的环节,导致系统运行效率的降低。

看到下面的部分,很多人应该会很诧异

A:what? 这都会影响运行效率?

B:答案是:肯定的。

从学Java开始,估计也有不少年了,简单的for循环肯定会写的。

下面我们来看两段代码:

int perSize = SnList.size() / threadNum;
for (int i = 0; i < threadNum; i++) {
    MultiThread thread = new MultiThread();
    thread.setRouteInfoList(SnList.subList(i * perSize, (i + 1) * perSize));
    thread.setRedisReportUtil(redisReportUtil);
    thread.setTotalCount(totalCount);
    thread.setTotal(total);
    thread.setRouteInfoService(routeInfoService);
    thread.setJ(j);
    thread.setCountDownLatch(countDownLatch);
    executorService.submit(thread);
}
for (int i = 0; i < (SnList.size() / threadNum); i++) {
    MultiThread thread = new MultiThread();
    thread.setRouteInfoList(SnList.subList(i * perSize, (i + 1) * perSize));
    thread.setRedisReportUtil(redisReportUtil);
    thread.setTotalCount(totalCount);
    thread.setTotal(total);
    thread.setRouteInfoService(routeInfoService);
    thread.setJ(j);
    thread.setCountDownLatch(countDownLatch);
    executorService.submit(thread);
}

各位老铁,发现有什么不同了么?

一个把for循环的第二个条件提取出来啦。

一个呢就稍微偷懒一下没这么干

有没有老铁觉得,这个问题不大,不会有太大差别呢?

把提取出去后,是节约了不少时间。

因为这个是去处理字符串类型的数据,且是每次都单独处理一个字符char。

所以,没使用foreach循环,只能这么简单的for i 循环了。

有时候看着这么简单的小变动,并不是什么大事儿,但是在处理海量数据的时候,是个大坑。

不是说不会写 for 循环,只是大家觉得这个不是个事儿,但是这个是问题的关键。希望大家不要挖坑给自己。

我是进阶的球儿,大家一起2019年的爬坑历程。感觉分享很给力的话给个赞,谢谢!!!有问题也可以下方留言沟通。