Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing the speed of insertion in java.util.Map/Set

is there a way to optimize the speed of the insertions in a java.util.Collection by specifying the order of the items ?

For example

java.util.Set<String> set = java.util.TreeSet<String>();

will this solution:

set.add("A");
set.add("B");
set.add("C");
set.add("D");
set.add("E");

be faster than this one (random order) ?

set.add("E");
set.add("D");
set.add("C");
set.add("A");
set.add("B");

(and the same question for the other collections: HashMap, hastable...)

Thanks

like image 287
Pierre Avatar asked Feb 22 '09 18:02

Pierre


People also ask

Which map is faster in Java?

The result is that HashMap is five times faster than Dictionary, almost the same as the performance on the Java VM (Consider the performance loss caused by transplantation).

Are Hashmaps slow Java?

Even if most of its operations are quite fast, resizing HashMap s is slow and hard to optimise, so the size should be calculated before building the map.

Is a HashMap efficient?

HashMap, being a hashtable-based implementation, internally uses an array-based data structure to organize its elements according to the hash function. HashMap provides expected constant-time performance O(1) for most operations like add(), remove() and contains(). Therefore, it's significantly faster than a TreeMap.

What is difference between MAP and HashMap in Java?

HashMap is a non-synchronized class of the Java Collection Framework that contains null values and keys, whereas Map is a Java interface, which is used to map key-pair values.


2 Answers

The easy answer is "time it and see".

The other answer is "it won't matter". This seems to be a micro-optimization that is hardly worth the effort. I think it falls into the category of "The Sad Tragedy of Micro-Optimization Theater".

like image 102
duffymo Avatar answered Nov 15 '22 10:11

duffymo


No for java.util.Map and java.util.Set, because these are interfaces, and there are different implementations.

For concrete implementations it is not a worthwhile optimization. If you have problems with performance chose a better suited implementation, or rethink what and how you need to store.

Inserting 5000 random numbers into a HashSet takes about a millisecond on a run-of-the-mill laptop, so how many millions of elements do you want to insert to make this kind of optimization worthwhile?

like image 44
starblue Avatar answered Nov 15 '22 10:11

starblue