Reputation: 1956
Just implemented a design where i had cached some data in hashmap and retrieved data from it instead querying the same data from DB.
Is my thinking correct ?
Upvotes: 4
Views: 375
Reputation: 1663
You can answer this yourself if you think through what happens when you talk to the database:
By comparison, a lookup on a hashed data structure requires a few memory accesses, which may take a few nanoseconds each. The difference is several orders of magnitude.
Upvotes: 3
Reputation: 16999
Should be much faster if the cost of computing the hash code is low, it also depends on the number of entries (as there will be more collisions)
Upvotes: 0
Reputation: 200148
The primary concern to take into account is the size of your cache: after a certain threshold, you are making more damage than good. For example, if the cache has a million entries, and each entry is 1 KB (not so hard to reach, given the overhead of each object), you have occupied a full gigabyte of heap. The performance of major GC will also be terrible in that case.
Upvotes: 2
Reputation: 16736
Look at it this way: to inquire the database, bytes have to be copied into memory anyway. Therefore, just accessing memory will always be faster than hitting a database.
Upvotes: 0
Reputation: 18123
Always hitting DB costlier than anything you do at code level..
Upvotes: 0
Reputation: 424983
Hitting a Collection is going to be several orders of magnitude faster than hitting a DB, especially one on another server (due to communication lag thereto)
That said:
Upvotes: 4
Reputation: 500217
Keeping a copy of the data in memory would almost certainly be faster than fetching it from the DB.
That said, there are further considerations to be taken into account:
Upvotes: 7