简体   繁体   English

Java集合内存消耗

[英]Java collections memory consumption

Say I instantiate 100 000 of Vectors 假设我实例化了10万个向量

a[0..100k] = new Vector<Integer>();

If i do this 如果我这样做

a[0..100k] = new Vector<Integer>(1);

Will they take less memory? 他们会占用更少的内存吗? That is ignoring whether they have stuff in them and the overhead of expanding them when there has to be more than 1 element. 那就是忽略它们中是否包含东西,以及当必须包含多个元素时扩展它们的开销。

According to the Javadoc , the default capacity for a vector is 10, so I would expect it to take more memory than a vector of capacity 1. 根据Javadoc ,向量的默认容量为10,因此我希望它比容量为1的向量占用更多的内存。

In practice, you should probably use an ArrayList unless you need to work with another API that requires vectors. 实际上,除非您需要使用另一个需要向量的API,否则您可能应该使用ArrayList

Well, sort of yes. 好吧,是的。 IIRC Vector initializes internally 16 elements by default which means that due to byte alignment and other stuff done by underlying VM you'll save a considerable amount of memory initially . IIRC Vector默认内部初始化16个元素,这意味着由于字节对齐和底层VM完成的其他工作,您最初会节省大量内存。

What are you trying to accomplish, though? 不过,您想完成什么?

Yes, they will. 是他们会。 Putting in reasonable "initial sizes" for collections is one of the first things I do when confronted with a need to radically improve memory consumption of my program. 当需要从根本上改善程序的内存消耗时,为集合放入合理的“初始大小”是我要做的第一件事。

When you create a Vector , you either specify the size you want it to have at the start or leave some default value. 创建Vector ,您可以指定希望它在开始时具有的大小,或者保留一些默认值。 But it should be noted that in any case everything stored in a Vector is just a bunch of references, which take really little place compared to the objects they are actually pointing at. 但是应该注意,在任何情况下, Vector存储的所有内容都只是一堆引用,与它们实际指向的对象相比,它们所占的位置很小。

So yes, you will save place initially, but only by the amount which equals to the difference between the default size and the specified multiplied by the size of a reference variable. 因此,是的,您将首先保存位置,但仅保存等于默认大小与指定大小之间的差值乘以参考变量大小的数量。 If you create a really large amount of vectors like in your case, initial size does matter. 如果像您这样创建大量矢量,则初始大小确实很重要。

Yes, it will. 是的,它会的。 By default, Vector allocates space for 10 elements. 默认情况下,Vector为10个元素分配空间。

Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.increment is zero. Vector()构造一个空向量,使其内部数据数组的大小为10,其标准容量增量为零。增量为零。

Therefore, it reserves memory for 10 memory references. 因此,它将为10个内存引用保留内存。

That being said, in real life situations, this is rarely a concern. 话虽如此,在现实生活中,这很少引起关注。 If you are truly generating 100,000 Vectors, you need to rethink your designincrement is zero. 如果您确实要生成100,000个向量,则需要重新考虑您的设计增量为零。

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

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