foreach for Iterator性能对比

代码如下

/**
 * Iterator,for,forEach比较
 * date 2018-12-14
 */
public class Test {
 
	private static final int COUNT = 10000;  
    	private static List<Person> persons = new ArrayList<Person>();  
  
	public static void init(){
		//初始化,生成对象个数
		Person person=null;
		for(int i=0;i<COUNT;i++){
			person=new Person(i,"张三"+i,i+"");
			persons.add(person);
		}
	}
	//Iterator遍历
	public static long testIterator(){
		//开始编译执行时间
		long start =System.nanoTime();
		Person person=null;
		for (Iterator<Person> iterator = persons.iterator(); iterator.hasNext();) {
			person = (Person) iterator.next();
			
		}
		//执行完后的时间
		long end =System.nanoTime();
		return (end- start) / (1000);
	}
	//foEach循环遍历
	public static long testForEach(){
		//开始编译执行时间
		long start =System.nanoTime();
		Person person=null;
		for(Person p:persons){
			person=p;
		}
		//执行完后的时间
		long end =System.nanoTime();
		return (end- start) / (1000);
	}
	//for循环遍历
	public static long testFor(){
		//开始编译执行时间
		long start =System.nanoTime();
		Person person=null;
		for(int i=0;i<persons.size();i++){
			person=persons.get(i);
		}
		//执行完后的时间
		long end =System.nanoTime();
		return (end- start) / (1000); 
	}
	public static void testRegxp(){
	}
	public static void main(String[] args) {
		init();
		System.out.println("Iterator迭代遍历的消耗时间为:"+testIterator());
		System.out.println("ForEach遍历的消耗时间为:"+testForEach());
		System.out.println("For循环遍历的消耗时间为:"+testFor());
		
	}
 
 
}

测试结果
1.此结果是在10万级下测试的,此时forEach循环遍历耗时较少,For和Iterator耗时较多

10万级测试结果

2.此结果是在1万级下测试的,此时for循环遍历耗时较少,ForEach和Iterator耗时较多
1万级测试结果

由于for循环count有内部和外部两种,又做了一次for循环count测试

1.count在内部

    $big_Array = range(0,1000000,1);
    $start_For_Time = microtime_float();
    for ($i=0;$i<count($big_Array);$i++) {  
            $i;
    }
    $end_For_Time = microtime_float();
    $for_Time = $end_For_Time - $start_For_Time;
    echo 'for循环遍历耗时:'.$for_Time.'<br>';  
    //for循环遍历(count在内部)耗时:0.039999961853027

2.count在外部

    $big_Array = range(0,1000000,1);
    $start_For_Time = microtime_float();
    $array_Count = count($big_Array);
    for ($i=0;$i<$array_Count;$i++) { 
          $i;
    }
    $end_For_Time = microtime_float();
    $for_Time = $end_For_Time - $start_For_Time;
    echo 'for循环遍历耗时:'.$for_Time.'<br>';    
    //for循环遍历(count在外部)耗时:0.023999929428101

结果:
1.10万级数据下测试结果为foreach性能最好
2.1万级数据下测试结果为for性能最好,且count在外部

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值