Map.clear()与新地图:哪一个会更好? [英] Map.clear() vs new Map : Which one will be better?

查看:291
本文介绍了Map.clear()与新地图:哪一个会更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图的语法地图<字符串,字符串> testMap =新的HashMap<字符串,字符串>(); 。 在这个图可以有1000个数据。

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

在我的应用程序需要新的数据列表,然后我必须清除地图。但是,当我看到Map.clear()的code为

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;
    }

我认识到,清晰的方法去在循环n次(其中n是在地图数据的数量)。所以,我想可以有一个方法来重新定义地图为 testMap =新的HashMap&LT;字符串,字符串&GT;(); 和pviously使用$ P $地图会被垃圾收集。

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.

您可以请指导我?

推荐答案

复杂的问题。让我们看看会发生什么。

Complicated question. Let's see what happens.

您实例化一个新的实例,这是支持新的阵列。因此,垃圾收集器应该清除的previous地图中的所有键和值,并清除自身引用。所以,O(n)的算法是反正执行,但在垃圾收集器线程。对于1000条记录,你将不会看到任何区别。 但。性能指南告诉你,它始终是最好不要创建新的对象,如果你能。所以,我会去clear()方法。

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!

这篇关于Map.clear()与新地图:哪一个会更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆