chrisben wrote:
sorry. I think my subject is misleading. My question is more general
for a collection class, like Queue, ArrayList or Hashtable, we can declare
them either as
new Queue(1000) or
new Queue()
My understanding is that fix size declaration may provide better memoery
allocation internally, but I am not sure whehter I will really gain anything
in performance. Since whenever I declare fix size, I always start a timed
bomb in the future which may explode if my data items go beyond that size and
I forget to handle it.
I see some leftover codes with hash,queue all declared as fixed size, which
I am thinking to change it since I assume that may bring me more trouble than
benefit.
Don't confuse "initial size" with "fixed size".
None of the data structures you mentioned are "fixed size" in .NET. All
expand to accommodate new items if necessary.
The difference between specifying an initial size and not is that you
can save yourself the cost of reallocation and copying. (The only
exception is Hashtable, which works differently, but still has no
maximum... in the case of Hashtable you're really talking about storage
/ retrieval efficiency, not reallocation.)
For example, if you say
ArrayList x = new ArrayList();
and then add 1000 elements to it, your array list will start off with
some default capacity (say, 10) and then when the 11th element is added
the capacity will be increased. The standard algorithm is to double the
size on each reallocation, but I'm not sure what .NET does internally.
If you already know that you are going to have 1000 entries in the
array list, you can declare it
ArrayList x = new ArrayList(1100);
or something and save yourself the reallocation. (I used 1100 because
if you "know" there's going to be 1000 and there are in fact 1001 then
it would cost you a reallocation and copy to fit that last element in.
If you're just guessing you might as well use an even number like
1000.)
So, no matter what, you're never going to "hit the limit" on these data
structures. All you're doing is saving the maching a bit of extra work
reallocating and copying the data if you know that you're going to need
lots of items.