简体   繁体   English

使用哈希映射而不是数组会产生空间开销吗?

[英]Is there space overhead to using a hash map instead of an array?

I was trying to implement a trie and read in an example implementation that it would be more space efficient to use a small array of size 26 to store the children because then you wouldn't have to waste space with a HashMap (the code was in Java, if that makes a difference) 我试图实现一个特里并在一个示例实现中阅读到,使用大小为26的小数组存储子代将更节省空间,因为那样您就不必浪费HashMap的空间了(代码在Java(如果有所作为)

But wouldn't a map be more space efficient since you don't necessarily need to store all 26 values? 但是,由于不必一定要存储所有26个值,地图会不会更加节省空间? Or is a HashMap object that contains Character objects as keys just more space because a simple int[] type does not use extra space in the background that the implementation for these more complex objects would use? 还是将包含Character对象作为键的HashMap对象留出更多空间,因为简单的int []类型在后台不会使用实现这些更复杂对象的额外空间?

Just wanting to check if maybe this person was mistaken or if there's some overhead involved in using object types like HashMap that I should be aware of. 我只是想检查一下这个人是否弄错了,或者使用诸如HashMap之类的对象类型是否涉及一些开销,我应该注意。

A hashmap stores keys and values, so if you were to implement a trie using a hashmap, you would be storing not only the values, but also the keys. 哈希图存储键和值,因此,如果要使用哈希图实现Trie,则不仅要存储值,还要存储键。 If you use an array, then the key is actually the index of the value in the array, so you do not have to store it anywhere. 如果使用数组,则键实际上是该值在数组中的索引,因此您不必将其存储在任何地方。

Besides that, hashmaps are less space efficient than arrays because they always have a load factor which is smaller than one, which is the same as saying that they keep more entries allocated than necessary due to the way they work. 除此之外,散列图的空间效率不及数组,因为散列图始终具有小于1的负载因子 ,这与说由于其工作方式而使它们保留的分配的条目多于必要数量相同。 I am not expanding on this, because it is not related to your issue, but if you are curious, search for hashmap load factor . 我不会对此进行扩展,因为它与您的问题无关,但是如果您很好奇,请搜索hashmap load factor

This is a classic programming compromise. 这是经典的编程折衷方案。 In this case, using a HashMap will take more space, but that may be a price you're willing to pay for improved performance. 在这种情况下,使用HashMap将占用更多空间,但这可能是您愿意为提高性能付出的代价。 Or it might not. 否则可能不会。 Depends on your problem. 取决于您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM