Search code examples
javalisthashmaphttpsession

Storing multiple hashmaps vs storing one list with all the hashmaps in java httpsession object


We need to store a hash map in httpSession once we retrieve the data from web service so that we don't fire this web service again. There could be multiple hash maps in the application. We could store them individually as a separate hash maps or store all of them in a list and store that single list object in httpSession.

Which could be the better approach from a performance and memory perspective in storing these objects? Separate hash maps or a list with all these hash maps.

One pros that I could think of which storing as separate hash map is that we need not iterate the list to find if the value is present or not.


Solution

  • Instead of storing it as a list of HashMap, why don't you store it as a hashmap of hashmap, which would avoid the iteration over list and you can get the required HashMap in O(1). Which makes it more efficient solution then the List of HashMap.

    For example :- if your hashmap is of type HashMap<String,String> , then you could create a HashMap>, where key is the unique identifier of HashMap which is stored. This key anyway you need if you want to store them separately.

    It is as same as storing these hashmap separately but its a cleaner approach, as you know that you only have to deal with 1 data-structure and will improve the code readability.

    Coming to performance or memory optimization, its difficult to guess, although I am guessing that there won't be much difference and you have to use some profiling tools like yourkit,AppDynamics, visualVM to figure that out.