Iterator迭代器和foreach增强for循环的效率比较

2018-01-30 11:01:24来源:oschina作者:小池仔人点击

分享
第七城市th7cn

package cn.jiguang.base64;


import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry;


import org.junit.Test;


public class CollectionTest {


public void JDK8DataTimeClockTest() { }


@Testpublic void foreachQuery() { int count = 0; Map map = new HashMap(); for (int i = 0; i < 100000; i++) {map.put("key=" + i, "value=" + i); }


long startTimeFor = System.currentTimeMillis(); for (Entry entry : map.entrySet()) {System.out.println(entry.getKey());System.out.println(entry.getValue());count++; } System.out.println("查询记录数=" + count); System.out.println("增强for查询耗时:" + (startTimeFor - System.currentTimeMillis()));}


@Testpublic void iteratorQuery() { int count = 0; Map map = new HashMap(); for (int i = 0; i < 1000000; i++) {map.put("key=" + i, "value=" + i); }


Iterator> iterator = map.entrySet().iterator(); long startTimeIterator = System.currentTimeMillis(); while (iterator.hasNext()) {String key = iterator.next().getKey();String value = iterator.next().getValue();System.out.println(key);System.out.println(value);count++; } System.out.println("查询记录数=" + count); System.out.println("迭代器Iterator查询耗时:" + (startTimeIterator - System.currentTimeMillis()));} }

第七城市th7cn

微信扫一扫

第七城市微信公众平台