map - Java : Iteration through a HashMap, which is more efficient? -
given following code, 2 alternative ways iterate through it,
is there performance difference between these 2 methods?
map<string, integer> map = new hashmap<string, integer>(); //populate map //alt. #1 (string key : map.keyset()) { integer value = map.get(key); //use key , value } //alt. #2 (map.entry<string, integer> entry : map.entryset()) { string key = entry.getkey(); integer value = entry.getvalue(); //use key , value }
i inclined think alt. #2
more efficient means of iterating through entire map
(but wrong)
your second options more efficient since doing lookup once compared n number of times in first option.
but, nothing sticks better trying out when can. here goes -
(not perfect enough verify assumptions , on machine anyway)
public static void main(string args[]) { map<string, integer> map = new hashmap<string, integer>(); // populate map int mapsize = 500000; int strlength = 5; for(int i=0;i<mapsize;i++) map.put(randomstringutils.random(strlength), randomutils.nextint()); long start = system.currenttimemillis(); // alt. #1 (string key : map.keyset()) { integer value = map.get(key); // use key , value } system.out.println("alt #1 took "+(system.currenttimemillis()-start)+" ms"); start = system.currenttimemillis(); // alt. #2 (map.entry<string, integer> entry : map.entryset()) { string key = entry.getkey(); integer value = entry.getvalue(); // use key , value } system.out.println("alt #2 took "+(system.currenttimemillis()-start)+" ms"); }
results (some interesting ones)
with int mapsize = 5000; int strlength = 5;
alt #1 took 26 ms
alt #2 took 20 ms
with int mapsize = 50000; int strlength = 5;
alt #1 took 32 ms
alt #2 took 20 ms
with int mapsize = 50000; int strlength = 50;
alt #1 took 22 ms
alt #2 took 21 ms
with int mapsize = 50000; int strlength = 500;
alt #1 took 28 ms
alt #2 took 23 ms
with int mapsize = 500000; int strlength = 5;
alt #1 took 92 ms
alt #2 took 57 ms
...and on
Comments
Post a Comment