Pan*_*mar 90 java collections performance android
我有一个Map作为语法Map<String, String> testMap = new HashMap<String, String>();.在此地图中可以有1000个数据.
当我的应用程序需要新的数据列表时,我必须清除Map.但是当我看到Map.clear()的代码为
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
我意识到clear方法循环n次(其中n是Map中的数据).所以我认为可以有一种方法来重新定义Map,因为testMap = new HashMap<String, String>();
之前使用的Map将是Garbage收集的.
但我不确定这将是一个好方法.我正在研究移动应用程序.
你能指导我吗?
小智 22
当你Map.clear()在大小的地图上说n...你要求GC清理2*n(键和值)对象.当您null对同一个Map 说时,您要求GC清理2*n+1(Map本身为1)对象.然后,您将不得不创建一个新的Map实例,这是另一个开销.所以去吧Map.clear().在实例化时,您最好预设Map的大小.
使用clear()方法的想法是从地图中删除对其他对象的引用,这样如果"地图被引用到其他地方",则键/值不会受到限制.
但是,如果您的地图是仅由您的特定代码使用的本地地图(即"地图"未在其他地方引用"),那么继续使用新地图,但设置1000引用为null将不会是一个重大的性能打击无论如何.
| 归档时间: |
|
| 查看次数: |
73695 次 |
| 最近记录: |