What is the best way to expand an array?

  • Thread starter Thread starter David Rogers
  • Start date Start date
D

David Rogers

Is this sequence about as efficient as I can get for sometimes expanding an
array?

MyClass [] MyFunc()
{
MyClass [] result = new MyClass [0];

{
// Do stuff that might possibly allocate an array and put entries in
it
// This path is usually executed
// ...
result = new MyClass[numEntries];
}

{
// Do stuff that might possibly add more entries to the previously
allocated array
// This path may be executed, but not usually
// ...
newResult = new MyClass[result .Length + newNumEntries];
result .CopyTo(newResult , 0);
result = newResult ;
}

return result;
}
 
Unless performance is a major issue, it would probably be easier just to use
an ArrayList

MyClass[] MyFunc()
{
ArrayList result = new ArrayList();
{
//do stuff to fill the result
}
return (MyClass[])result.ToArray(typeof(MyClass));
}
 
David Rogers said:
Is this sequence about as efficient as I can get for sometimes expanding an
array?

Yes - but most of the time when you want a dynamically-sized list of
things, you might as well use ArrayList instead.
 
David,
Is this sequence about as efficient as I can get for sometimes expanding an
array?
For the most part yes.

You could do as the ArrayList & StringBuilder classes do.

Over allocate the array, and keep track of how many items are actually in
the array. When the array gets full, then you double it in size. Of course
that may be what you are already doing ;-)

There was a discussion about creating an new ArrayList like class for
structures in the vb.dotnet.technical newsgroup (on the news.devx.com news
server). Look for a thread titled 'Dynamic array of structure variables,
starting 2 Aug 2003.

http://news.devx.com/cgi-bin/dnewsweb.exe?cmd=xover&group=vb.dotnet.technical

I gave a start of a class to create a dynamic array of structures, that over
allocates the underlying array.

Hope this helps
Jay



David Rogers said:
Is this sequence about as efficient as I can get for sometimes expanding an
array?

MyClass [] MyFunc()
{
MyClass [] result = new MyClass [0];

{
// Do stuff that might possibly allocate an array and put entries in
it
// This path is usually executed
// ...
result = new MyClass[numEntries];
}

{
// Do stuff that might possibly add more entries to the previously
allocated array
// This path may be executed, but not usually
// ...
newResult = new MyClass[result .Length + newNumEntries];
result .CopyTo(newResult , 0);
result = newResult ;
}

return result;
}
 
Hi David,

Use an ArrayList instead, it grows and shrinks automatically. The ArrayList
is not strongly typed but once you've finished populating it you can use the
CopyTo method to copy the data into a strongly typed array.
 
Back
Top