Map.clear() vs new Map:哪个更好? [英] Map.clear() vs new Map : Which one will be better?

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

问题描述

我有一个 Map 作为语法 Map;testMap = new 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() 的代码为

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

我意识到 clear 方法循环了 n 次(其中 n 是 Map 中的数据数).所以我认为有一种方法可以将该 Map 重新定义为 testMap = new HashMap();并且以前使用的 Map 将被垃圾收集.

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.

您实例化一个新实例,该实例由新数组支持.因此,垃圾收集器应该清除之前映射中的所有键和值,并清除对自身的引用.所以无论如何都要执行 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() vs new Map:哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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