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

Pankaj Kumar picture Pankaj Kumar · Jul 20, 2011 · Viewed 80k times · Source

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?

Answer

Vladimir Ivanov picture Vladimir Ivanov · Jul 20, 2011

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!