Performance comparison of different ways to iterate over HashMap

本文对比了四种遍历Java HashMap 的方法:使用 entrySet() 和 foreach 循环,使用 keySet() 和 foreach 循环,使用 entrySet() 和 Iterator,使用 keySet() 和 Iterator。通过存储100万条键值对并遍历,记录了每种方法的执行时间,发现使用 entrySet() 相对于 keySet() 在性能上有明显优势。

Performance comparison of different ways to iterate over HashMap


We have already learned about how HashMap in java works internally. If my last similar post, I tried to compare different “for loop” flavors available in java. These studies usually help in setting up best practices for your next project.

I this post, I decided to compare traversal in hash map in java. HashMap is very frequently used class and most of the times we just fetch the value using get(Object key) method provided by class. But at times it is required to iterate over whole Map and fetch all key-value pairs stored in it. For example, analyzing all request parameters sent from client. If you are using this, the for every client you will be iterating whole map at least once in your code.

If you are using this type of iteration many places in code and there are large number of requests then you surely would like to optimize your iteration code to make best use of it. My below given analysis will help you to decide your next step.

Lets start with different ways to iterating over HashMap first:

1) Using enrtySet() in for each loop

for (Map.Entry<String,Integer> entry : testMap.entrySet()) { entry.getKey(); entry.getValue(); }

2) Using keySet() in for each loop

for (String key : testMap.keySet()) {
    testMap.get(key);
}

3) Using enrtySet() and iterator

Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator(); while(itr1.hasNext())
{
    Map.Entry<String,Integer> entry = itr1.next(); entry.getKey(); entry.getValue(); }

4) Using keySet() and iterator

Iterator itr2 = testMap.keySet().iterator(); while(itr2.hasNext())
{
    String key = itr2.next(); testMap.get(key); }

Now lets compare their performances for a common data set stored in map. I am storing 10 lacs key value pairs in map and will iterate over map in all four ways. I will also fetch key and value from map for all 10 lacs entries in best suitable way. Then i will capture the time taken by each way.

package com.howtodoinjava.performance; import java.util.Calendar; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class DifferentWaysToIterateOverHashMap {

    static HashMap<String,Integer> testMap = new HashMap<String,Integer>(); static
    {
        for(int i=0; i< 10_00_000; i++) {
            testMap.put("key_" + i, i); }
    }

    public static void main(String[] args) {

        long startTime = Calendar.getInstance().getTimeInMillis(); //First way using entrySet in for-each loop
        for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
            entry.getKey(); entry.getValue(); }

        System.out.println("Using entrySet() in for-each loop : " + (Calendar.getInstance().getTimeInMillis() - startTime)); startTime = Calendar.getInstance().getTimeInMillis(); //Second way using keySet() in for-each loop
        for (String key : testMap.keySet()) {
            testMap.get(key); }

        System.out.println("Using keySet() in for-each loop : " + (Calendar.getInstance().getTimeInMillis() - startTime)); startTime = Calendar.getInstance().getTimeInMillis(); //Third way using Iterator on entrySet() in while loop
        Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator(); while(itr1.hasNext())
        {
            Map.Entry<String,Integer> entry = itr1.next(); entry.getKey(); entry.getValue(); }

        System.out.println("Using entrySet() and iterator : " + (Calendar.getInstance().getTimeInMillis() - startTime)); startTime = Calendar.getInstance().getTimeInMillis(); //Third way using Iterator on keySet() in while loop
        Iterator<String> itr2 = testMap.keySet().iterator(); while(itr2.hasNext())
        {
            String key = itr2.next(); testMap.get(key); }

        System.out.println("Using keySet() and iterator : " + (Calendar.getInstance().getTimeInMillis() - startTime)); }
}

Output of above program (in milliseconds) :

Using entrySet() in for-each loop : 50
Using keySet() in for-each loop : 76
Using entrySet() and iterator : 50
Using keySet() and iterator : 75

Observations:

10 lacs is very big number of most the application requirements. Even though the difference is not very substantial in milliseconds, as compare to it was very big in case of for loops. I believe most of us can live with such a minor difference.

But if you want to be very specifically make the conclusion, using entry set is more powerful and yields better performance as comparing to using key set for iteration. Result varies from 20% – 50% when above program is executed multiple times.

Please do let me know of your thoughts about above analysis.

Happy Learning !!

from http://howtodoinjava.com/2013/04/01/performance-comparison-of-different-ways-to-iterate-over-hashmap/

转载于:https://my.oschina.net/doctor2014/blog/385910

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值