HashMap 的遍历方法和效率测试

原创 hashmap

HashMap 遍历是开发者经常遇到的,遍历的方式也有多种,但是哪种方式最优呢,此次做了下测试,请看测试过程和结果。

测试说明:拿 100W 条记录塞进了 HashMap 中进行遍历,遍历时间均为毫秒。

测试结果:

start put elements!
start test...
map size:1000000
method1 spend:94
method2 spend:78
method3 spend:94
method4 spend:47

结果表明,第二种方式要有于 1 和 3,第四种无可比性,因为它只是遍历出了 value,如果不需要 key 可以使用第四种方式。

附带测试程序:

HashMapTraverser.java

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

/**
 * HashMap 遍历测试程序
 * @author liuqianfei
 */
public class HashMapTraverser
{
    public static void main(String[] args)
    {
        Map _map = new HashMap();
        System.out.println("start put elements!");
        for (int i = 0; i < 1000000; i++)
        {
            _map.put("key" + i, "value" + i);
        }
        System.out.println("start test...");
        long step1 = System.currentTimeMillis();
        traverserOne(_map);
        long step2 = System.currentTimeMillis();
        traverserTwo(_map);
        long step3 = System.currentTimeMillis();
        traverserThree(_map);
        long step4 = System.currentTimeMillis();
        traverserFour(_map);
        long step5 = System.currentTimeMillis();
        System.out.println("map size:" + _map.size());
        System.out.println("method1 spend:" + (step2 - step1));
        System.out.println("method2 spend:" + (step3 - step2));
        System.out.println("method3 spend:" + (step4 - step3));
        System.out.println("method4 spend:" + (step5 - step4));
    }

    /**
     * 第一种遍历方法
     * 
     * @param map
     */
    public static void traverserOne(Map map)
    {
        Set _set = map.keySet();
        for (String _s : _set)
        {
            // System.out.println(s + "," + map.get(s));
            String _key = _s;
            String _value = map.get(_s);
        }
    }

    /**
     * 第二种遍历方法
     * 
     * @param map
     */
    public static void traverserTwo(Map map)
    {
        Set> _entryseSet = map.entrySet();
        for (Map.Entry _entry : _entryseSet)
        {
            String _key = _entry.getKey();
            String _value = _entry.getValue();
        }
    }

    /**
     * 第三种遍历方法
     * 
     * @param map
     */
    public static void traverserThree(Map map)
    {
        Iterator it = map.keySet().iterator();
        while (it.hasNext())
        {
            String _key = it.next();
            String _value = map.get(_key);
        }

    }

    /**
     * 第四种遍历方法
     * 
     * @param map
     */
    public static void traverserFour(Map map)
    {
        Iterator it = map.values().iterator();
        while (it.hasNext())
        {
            String _val = (String) it.next();
        }
    }
}
如果觉得这对你有用,请随意赞赏,给与作者支持
评论 0
最新评论