working with C# arrays (memory, efficiency, speed)

When working with an array (of bytes but could be anything) how do these two approaches compare in terms of efficiency, speed, etc. Why would one prefer one over the other?

First approach

byte[] myArray=new byte[100];

useArray(myArray);
useArray(myArray);
useArray(myArray);

//where

void useArray(byte[] MyArray)
{
   //do something with the elements of MyArray
}

Second Approach

byte[] myArray=new byte[100];

myArray= useArray2(myArray);
myArray= useArray2(myArray);
myArray= useArray2(myArray);
//where

byte[] useArray2(byte[] MyArray)
{
    byte[] tempArray= new byte[100];
   //do EXACTLY the same as useArray but store the results in tempArray 
   return tempArray;
}

Take into account that the option 2 is leaving memory to be garbage collected at some point in time, everytime it calls useArray2. Also the functions are going to be called repeatedly.

So which is more efficient, or preferable?

1 answer

  • answered 2017-12-06 02:03 Jonathan Wood

    Let's see. Your first example allocates a single, 100-byte array.

    Your second example allocates four 100-byte arrays, all of which will need to be deallocated. And you may or may not be copying data between those arrays.

    Isn't it clear that the first is more efficient?