views:

103

answers:

5

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.

+2  A: 

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?

Esko
+1  A: 

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.

MarkPowell
+2  A: 

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.

jkff
+2  A: 

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.

Malcolm
+5  A: 

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.

Alex M.
Cheers, yes i was rather giving an example, but noted!
Recz