初始化HashMap的最佳方式 [英] Best way to initialize a HashMap

查看:160
本文介绍了初始化HashMap的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常做例如

  HashMap< String,String> dictionary = new HashMap< String,String>(); 

我开始考虑它,据我所知,一个 HashMap 通过哈希表在引擎盖下实现。

使用哈希存储在表中的对象,以找到它们应该存储在表中的位置。



事实上,我没有在字典的构造上设置大小,使得性能下降? br>
Ie在构建过程中哈希表的大小是多少?是否需要为元素分配新的内存?

或者我对这个概念感到困惑?

默认容量和负载是否足够或应该花时间对于实际的数字?

解决方案


事实上,我没有设置一个大小的建设的字典使得性能下降?


取决于您要存储在 HashMap中的多少以及之后的代码将如何使用。如果你可以在前面给它一个球场数据,可能会更快,但是:如果迭代性能很重要,那么设置初始容量太重要了[...] 1 ,因为迭代时间与容量成正比。 p>

在非性能关键的代码段中执行此操作将被视为过早优化。如果您要超越JDK作者,请确保您的测量结果表明您的优化很重要。


什么是大小在构建期间的哈希表?


根据 API文档,16。


是否需要为元素分配新内存?


是的。每次都比加载因子(默认值= .75)更全面,它将重新分配。


默认容量和负载是否足够>

只有你可以告诉。配置您的程序,看看它是否花费太多时间在 HashMap.put 中。如果不是,不要打扰。


I usually do e.g.

HashMap<String,String> dictionary = new HashMap<String,String>();

I started to think about it, and as far as I know a HashMap is implemented under the hood via a hash table.
The objects are stored in the table using a hash to find where they should be stored in the table.

Does the fact that I do not set a size on the construction of the dictionary makes the performace decrease?
I.e. what would be the size of the hash table during construction? Would it need to allocate new memory for the table as elements increase?
Or I am confused on the concept here?
Are the default capacity and load adequate or should I be spending time for the actual numbers?

解决方案

Does the fact that I do not set a size on the construction of the dictionary makes the performace decrease?

Depends on how much you're going to store in the HashMap and how your code will use it afterward. If you can give it a ballpark figure up front, it might be faster, but: "it's very important not to set the initial capacity too high [...] if iteration performance is important" 1 because iteration time is proportional to the capacity.

Doing this in non-performance-critical pieces of code would be considered premature optimization. If you're going to outsmart the JDK authors, make sure you have measurements that show that your optimization matters.

what would be the size of the hash table during construction?

According to the API docs, 16.

Would it need to allocate new memory for the table as elements increase?

Yes. Every time it's fuller than the load factor (default = .75), it reallocates.

Are the default capacity and load adequate

Only you can tell. Profile your program to see whether it's spending too much time in HashMap.put. If it's not, don't bother.

这篇关于初始化HashMap的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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