1) Hashtable
2) Synchronized Map
3) ConcurrentHashMap
I am shooked to see that ConcurrentHashMap took the maximum time to perform similar operations. I executed the program several times and the order remained the same throughout.
I have attached the source code for the same. Please let me know if I am doing something wrong.
Download link : http://www.2shared.com/file/k5LUxd-1/src.html
Look for “Save file to your PC : click here”
#1 by Peter Lawrey on June 20th, 2010
Quote
The key problem you have here is that your testing framwork is much more heavy weight than the thing you are testing. This means your results are more of an indication as to how your framework is perfoming than the thing you are testing.
Perhaps the most important lessons here are that
- when optimising, start with the most expensive operation, don’t guess, use a profiler and your judgement after that.
- whatever you do with the Map is far more likely to be important the cost of the Map itself, for any real application.
If you were to optimise it, I would suggest
- using a thread pool which is the size of the number of cores you have.
- make each task in the thread pool perform a singiciant piece of work, one put() is likely to be trivial compared to the cost of even adding a task to a thread pool. Certainly trivial compared with starting a new thread. Try 1000 puts or more.
- Use System.nanoTime for more accurate benchmarks. Using Date is not as expensive as Calendar but its one of the most expensive and least accurate ways to benchmark.
- Don’t use new objects for keys or values. I would pre-generate them all and only time the start and the end (with nanoTime), not the timing for each element as you have done. Taking the System.currentTimeMillis() (which Date does) can be more expensive than put().
#2 by Peter Lawrey on June 20th, 2010
Quote
#3 by Asim on June 20th, 2010
Quote
I will try again keeping your suggestions in mind and post my findings. I know people would have done that already but I dont want to keep this post incomplete.