Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtable vs HashMap performance in single threaded app

I know that Hashtable is synchronized so it is safe to be used in multithread app and HashMap is not.

I am wondering if there is any performance difference between these two in a single thread app.

(Or, when to use one over the other?)

like image 272
caesarkim Avatar asked Dec 12 '22 11:12

caesarkim


1 Answers

If you want a thread safe collection you can use ConcurrentHashMap or Collections.synchronizedMap() with LinkedHashMap or HashMap. If you don't need a thread safe collection you can use just the last two. Hashtable has been retro fitted to support Map with generics but it also comes with alot of legacy methods which do the same thing or much the same thing.

Hashtable can be used, however IMHO using one of the many other options which have been developed later would be a cleaner solution. If you have a library which needs a Hashtable, then you need to use it, but otherwise I would use a class which does what you need, follows best practice with a minimum of legacy methods.

The performance difference is likely to be about 0.5 us per call. This may or may not be significant.

However, if you don't need a type to be thread safe, there is no good reason to use the synchronized version. If you need a type to be thread safe, you can't use a type which is not without some thread safety guard.

like image 62
Peter Lawrey Avatar answered Jan 21 '23 09:01

Peter Lawrey