Dynamic Arrays

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Is there a high performance way in .Net to dynamically build single dimension
arrays when the number of elements in the array is unknown until after the
array is built? (i.e. I only need the array to grow, I don't need to remove
elements)

I noticed that Dim myVar As List(of X) gets converted to Dim myVar() As X
when returned from a web service. I'd like to build a single code base that
supports either using web services (Tiers) or tightly linked assemblies
(Layers). It would appear for that to work I'll need to use Arrays instead
of the new generics.

Thanks,

Larry
 
Larry,
No, there isn't. An array, once created, has a fixed upperBound. You can use
the ArrayList class as an alternative.
Peter
 
the array list uses an array under the covers (just keeps copying to new
bigger ones as items are added), so you want to give it a good hint on the
initial size.

-- bruce (sqlwork.com)
 
Is there a high performance way in .Net to dynamically build single dimension
arrays when the number of elements in the array is unknown until after the
array is built? (i.e. I only need the array to grow, I don't need to remove
elements)

I noticed that Dim myVar As List(of X) gets converted to Dim myVar() As X
when returned from a web service. I'd like to build a single code base that
supports either using web services (Tiers) or tightly linked assemblies
(Layers). It would appear for that to work I'll need to use Arrays instead
of the new generics.

Thanks,

Larry

If you are looking for high performance, you should switch to a
generic List.

List<int> myList = new List<int>();
myList.Add(1);
myList.Add(2);
etc.

When 2.0 came out, I switched from an ArrayList to a Generic List and
saw a 15x improvement in speed. (of course, mileage my vary...)

The reason is because generic's create native types for the CLR to
process. ArrayList's have to box and unbox on every reference. Ouch.

Good luck.


Peter Kellner
http://peterkellner.net
 
As Peter B. and Peter K. pointed out, an ArrayList or a generic List are
probably better, but be aware that you can resize arrays in .NET.
In .NET 2, you can use Array.Resize to resize single dimension arrays. Be
aware that it does copy the contents to a new array internally on each
'Resize' call. This is the main reason why the alternatives mentioned are
faster.
For multi-dimensional arrays, you can use the approach I discuss here:
http://www.tangiblesoftwaresolutions.com/Articles/CSharp Equivalent to VB ReDim Preserve.htm
--
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
Instant C++: C# to C++ converter & VB to C++ converter
Instant J#: VB to J# converter
 
Back
Top