Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest and most efficient way of searching a key-value pair in Java?

DISCLAIMER:
This question was not meant to be argumentative!

What is fastest and less memory draining way of searching a key-value pair? I will be storing items in a key-value like relation and I need to access them quickly. Should I use a SQLite database? A Map? A Hashtable? A HashMap? Please give some advantages/disadvantages of using whatever method of searching.

like image 230
Mohit Deshpande Avatar asked Jun 18 '10 08:06

Mohit Deshpande


2 Answers

Any hash-based Map structure is the way to go as long as your hash function for the key is efficient. You can use value id:s as the result for the lookup to conserve memory during search.

If your data is already in database though, you can leave this search entirely to the RDBMS, after all they're made for this stuff.

like image 143
Esko Avatar answered Sep 21 '22 21:09

Esko


If your data is in memory, Maps in general are your friends - they are meant for this.

Don't use a Hashtable however. It is much slower than newer Map implementations. because its methods are synchronized, which most of the time is not needed (and when needed, there is a much better alternative - see below).

In single-threaded context, HashMap is probably going to be OK.

If you need thread safety, use a ConcurrentHashMap.

like image 7
Péter Török Avatar answered Sep 21 '22 21:09

Péter Török