0
点赞
收藏
分享

微信扫一扫

性能优化-测试Contiue是否能对For循环起到的优化作用

精进的医生 2022-03-11 阅读 69


代码示例
package com.cwl.po;

import java.util.ArrayList;
import java.util.List;

/**
* @program: cwl-performance-optimization
* @description: 测试Contiue是否能对For循环起到的优化作用
* @author: ChenWenLong
* @create: 2019-11-22 11:43
**/
public class TestContinueLoop {

// 业务场景: for循环遍历集合时总会遇到我们想要的数据,也有不想要的数据参合在一起的时候
// 我们是使用判定条件将不需要的跳过 或者直接选择想要的数据进行处理,哪一种的性能更好呢
public static void main(String[] args) {
System.out.println(testContinue());
System.out.println(testNotContinue());
// 结论:最终证明,使用continue并没有是的for循环性能更好
}

/**
* 功能描述:
* 〈测试for循环中遇到特定条件不使用contiue〉
*
* @params : []
* @return : long
* @author : cwl
* @date : 2019/11/22 11:46
*/
private static long testNotContinue() {
List<Integer> resultList = new ArrayList<>();
long begin = System.currentTimeMillis();
for(int a=0;a<10000000;a++){
if(a % 2 == 0){
continue;
}
resultList.add(a);
}
long end = System.currentTimeMillis();
return end - begin;
}

/**
* 功能描述:
* 〈测试for循环中遇到特定条件使用contiue〉
*
* @params : []
* @return : long
* @author : cwl
* @date : 2019/11/22 11:47
*/
private static long testContinue() {
List<Integer> resultList = new ArrayList<>();
long begin = System.currentTimeMillis();
for(int a=0;a<10000000;a++){
if(a % 2 == 1){
resultList.add(a);
}
}
long end = System.currentTimeMillis();
return end - begin;
}
}



举报

相关推荐

0 条评论