开发者

Java collections memory consumption

Say I instantiate 100 000 of Vectors

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.

In practice, you should probably use an ArrayList unless you need to work with another API that requires vectors.


When you create a Vector, you either specify the size you want it to have at the start or leave some default value. 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.

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.


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.

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.


Yes, it will. By default, Vector allocates space for 10 elements.

Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.increment is zero.

Therefore, it reserves memory for 10 memory references.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜