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
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).
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.
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.
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.
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".
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With