Map.clear() vs new Map : Which one will be better?

JavaAndroidPerformanceCollections

Java Problem Overview


I have a Map as syntax as Map<String, String> testMap = new HashMap<String, String>();. In this map there can be 1000 data.

When my application requires to new list of data, then I must clear the Map. But when I saw the code of Map.clear() as

/**
     * Removes all of the mappings from this map.
     * The map will be empty after this call returns.
     */
    public void clear() {
        modCount++;
        Entry[] tab = table;
        for (int i = 0; i < tab.length; i++)
            tab[i] = null;
        size = 0;
    }

I realize that clear method goes in loop for n times (Where n is number of data in Map). So I thought there can be a way to redefine that Map as testMap = new HashMap<String, String>(); and previously used Map will be Garbage collected.

But I am not sure this will be a good way. I am working on mobile application.

Can you please guide me?

Java Solutions


Solution 1 - Java

Complicated question. Let's see what happens.

You instantiate a new instance, which is backed with new array. So, garbage collector should clear all the key and values from the previous map, and clear the reference to itself. So O(n) algorithm is executed anyway, but in the garbage collector thread. For 1000 records you won't see any difference. BUT. The performance guide tells you that it is always better not to create new objects, if you can. So I would go with clear() method.

Anyway, try both variants and try to measure. Always measure!

Solution 2 - Java

When you say Map.clear() on a Map of size n... You are asking the GC to clean up 2*n (Key & Value) objects. When you say null to the same Map, you are asking the GC to clean up 2*n+1 (1 for the Map itself) objects. Then you will have to create a new Map instance yet another overhead. So go for Map.clear(). You will be wise to preset the size of the Map while instantiating it.

Solution 3 - Java

I thought Creating object in java more expensive in terms of memory,so it is better to you go with .clear(),so you are using same object instead of creating new one

Solution 4 - Java

The idea of having clear() method is to remove references to other objects from the map, so that the key/values are not held up from gcing if the "map is referenced somewhere else".

But if your map is a local map only used by your specific code( i.e. "map is 'not' referenced somewhere else") then go ahead and use a new map instead, but setting a 1000 references to null wont be a big performance hit anyway.

Solution 5 - Java

don't forget the repopulation of the map

if you don't specify the capacity on the new map you will get quite a bit of overhead on the newly created map because of rehashes (which each are O(n) (at the time) and happen O(log(n)) times while this might amortize to O(n) total but if they don't happen in the first place you will still be better of)

this won't happen with the cleared map because the capacity doesn't change

Solution 6 - Java

I think calling new HashMap() is a better idea since it will not have to do as much processing as clearing the hashmap. Also, by creating a new hashmap you are removing the chance that the hashmap may still be binded to the control that uses the data, which would cause problems when the hashmap is to be cleared.

Solution 7 - Java

The map.clear() that will remove all data. Note that this will only discard all entries, but keep the internal array used to store the entries at the same size (rather than shrinking to an initial capacity). If you also need to eliminate that, the easiest way would be to discard the whole HashMap and replace it with a new instance. That of course only works if you control who has a pointer to the map.

As for reclaiming the memory, you will have to let the garbage collector do its work.

Are your values also Long? In this case, you may want to look at a more (memory-) efficient implementation than the generic HashMap, such as the TLongLongHashMap found in the GNU Trove library. That should save a lot of memory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPankaj KumarView Question on Stackoverflow
Solution 1 - JavaVladimir IvanovView Answer on Stackoverflow
Solution 2 - JavaTanveerView Answer on Stackoverflow
Solution 3 - JavasunriserView Answer on Stackoverflow
Solution 4 - JavaSuraj ChandranView Answer on Stackoverflow
Solution 5 - Javaratchet freakView Answer on Stackoverflow
Solution 6 - JavaA. AbiriView Answer on Stackoverflow
Solution 7 - JavaPratikView Answer on Stackoverflow