Prob: There is two methods to change size of array in C#. Using a template of a Benchmark program from this informative site, I checked the two ways:
Array.Resize VS Array.CopyTo VS Loop
Conclusion: sometime build it your self is not that better then using the build-in commands…
Array.Resize took 30253 ms
Arryay.CopyTo took 29649 ms
Loop took 58323 ms
Solution:
Here is the code that I use
class Program
{
public static void AddCell1(ref double[] vector,int num)
{
int size = vector.Length;
Array.Resize(ref vector,size+1);
vector[size] = num;
}
//————————————————-public static void AddCell2(ref double[] vector,int num)
{
double[] tempVec = new double[vector.Length+1];
vector.CopyTo(tempVec,0);
tempVec[vector.Length] = num;
vector = tempVec;
}
//————————————————-public static void AddCell3(ref double[] vector,int num)
{
double[] tempVec = new double[vector.Length+1];
for (int i = 0; i < vector.Length ; i++) {
tempVec[i] = vector[i];
}
tempVec[vector.Length] = num;
vector = tempVec;
}
//————————————————-public static void Main(string[] args)
{
Console.WriteLine(“Hello World!”);double[] arr1 = new double[]{};
double[] arr2 = new double[]{};
double[] arr3 = new double[]{};Stopwatch s1 = Stopwatch.StartNew();
for (int i = 0; i < 100000; i++)
AddCell1(ref arr1,i);
s1.Stop();Stopwatch s2 = Stopwatch.StartNew();
for (int i = 0; i < 100000; i++)
AddCell2(ref arr2,i);
s2.Stop();Stopwatch s3 = Stopwatch.StartNew();
for (int i = 0; i < 100000; i++)
AddCell3(ref arr3,i);
s3.Stop();// TODO: Implement Functionality Here
Console.WriteLine(“{0},{1},{2}”,
s1.ElapsedMilliseconds,
s2.ElapsedMilliseconds,
s3.ElapsedMilliseconds);
Console.Write(“Press any key to continue . . . “);
Console.ReadKey(true);
}
}