System.Collections.Generic.List<int> myList = new System.Collections.Generic.List<int>(100);

  • Thread starter Thread starter DR
  • Start date Start date
D

DR

System.Collections.Generic.List<int> myList = new
System.Collections.Generic.List<int>(100);

Does this preallocate 100 integers?

Also, is there any way to preallocate an array of objects all at once?

MyOb[] al= new MyOb[100];

for (int z = 0; z < nCount; z++)

{

al[z] = new MyOb();

}



Can i avoid all these new and just allocate an array of MyOb all at once?
 
System.Collections.Generic.List<int> myList = new
System.Collections.Generic.List<int>(100);

Does this preallocate 100 integers?

It "Initializes a new instance of the List(T) class that is empty and
has the specified initial capacity". RTFM.
Also, is there any way to preallocate an array of objects all at once?
Yes.


MyOb[] al= new MyOb[100];

You just did.
for (int z = 0; z < nCount; z++)

{

    al[z] = new MyOb();

}

Can i avoid all these new and just allocate an array of MyOb all at once?
 
DR said:
System.Collections.Generic.List<int> myList = new
System.Collections.Generic.List<int>(100);

Does this preallocate 100 integers?

Well, yes and no.

Internally, the list classes uses an array. In the above case, the array
is scaled to 100 items to begin with. As soon as you add the 101th item,
the list is resized to hold more.

Note that a capacity of 100 elements does not mean the list contains 100
items. It just means that the internal data structure won't be resized
until you add more than the capacity number of items. The list always
starts out empty regardless of its capacity.

Increasing the capacity involves creating a new array with the new
capacity, copying over all the items the list is currently holding to
the new array, and replacing the reference to the old array with a
reference to the new array.

Because of the "copying over all the items" part, increasing the
capacity of a list includes progressively more overhead as the number of
elements in the list increases.

Thus, you should specify the number if you know in advance how many
items you intend to add, to avoid needless overhead resizing while
growing the list.

The current algorithm is something like this:

- initial default list has a capacity of 0 items
- grow to a capacity of 4 items on first add
- whenever you add an item to a "full list", double its capacity

The above could be wrong, I can't remember where I read them.
Also, is there any way to preallocate an array of objects all at once?

MyOb[] al= new MyOb[100];

for (int z = 0; z < nCount; z++)

{

al[z] = new MyOb();

}



Can i avoid all these new and just allocate an array of MyOb all at once?

Not really..

Well, you *can* write this:

MyOb[] al = { new MyObj(), new MyOb(), new MyOb(), ... };

But I'd hardly do that for 100 objects.
 
Back
Top