Alternative to ArrayList.Add()

  • Thread starter Thread starter Tristan
  • Start date Start date
T

Tristan

Hi,

My code reads through a file of shapes adding each
one to an ArrayList as it does so.

The problem is that for files with large numbers of
shapes, calling ArrayList.Add(MyShape) is
exceptionally slow.

There is no way of knowing how many shapes need to
be read in so I can't set the ArrayList capacity
and use array indexing to add the shape objects.

I am prepared to use another collection if it
will be quicker and allow quick addition and
retrieval of objects (not so worried about
insertions and deletions), would SortedList.Add()
be any quicker?

Is there any way around this problem?

Any help will be much appreciated.

Tristan.
 
SortedList would be slower since it is a specialization of ArrayList in a way.
A Hashtable would be faster to insert, but possibly slower to use later.

I don't see where pre-initing a 200 element ArrayList and then using that would
be very slow though. Once the ArrayList gets a good number of items, it grows
itself pretty darn fast.
 
Define "Shape"?;

It might not be the collection that's the problem, but the amount and the
size of objects that you're shoving into it...

Also, it would be a good idea to write some code that tries to guess what
the initial capacity capacity of the ArrayList should be...

Remember:
"Capacity is always greater than or equal to Count. If Count exceeds
Capacity while adding elements, the capacity of the list is doubled by
automatically reallocating the internal array."

Reallocation of Large arrays can be slow - if you have an idea of how many
elements you're gonna have then add 10%, you'll probably see a significant
gain in perf.

And don't forget to TrimToSize().

Hope it helps;
Josh.
 
Back
Top