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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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() {
        
    }

    @Test
    public 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()));
    }

    @Test
    public 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()));
    }
}
 

转载于:https://my.oschina.net/u/3744350/blog/1615222

你可能感兴趣的:(java,c/c++,python)