Copy Part Of An Array To Another Array In C#

Copy Part Of An Array To Another Array Banner

Introduction

In C#, you may want to do a partial copy of an array to another for various reasons. It could be copying the entire array is more expensive or just too big if you are working with a lot of data. It can be more memory efficient.

This is more important in low-memory use cases such as embedded systems. Or You may face memory limitations in 32-bit applications. In today's applications, memory usage usually isn't a problem with 64-bit having access to large amounts of memory. But you still don't want to be wasteful of that resource because there may other applications running at the same time.

In general, it is good programming practice to only do what is needed. The other advantage is that it is faster to only copy part of an array rather than the whole array. If you have an array of a million objects and you only need to copy a few thousand then this copy operation would over time be more efficient. This of course works best when you can copy chunks of data at a time. Since an array is a continuous block of memory having a range of data is best and so make sure to organize your data as such so that a block of data can be copied at a time.

Also, another area is that copying only part of the array could lead to more efficient code. Let me explain. If you have a subsection of data in an array. It could lead to less complicated code if you have an array that is dedicated to the task.

Video With Examples

Is The Destination Array Length Equal To Source Array Length?

The first question we need to ask is the destination array equal to or smaller than the source array. If the destination array is the same size as the part we are taking from the source array then that is called a subsection or slice of the source array. Then you would take a look at an article I've written that deals with exactly that called Best Solution For Slicing Arrays

If the destination array is of equal size to the source array then read on as I will cover in more detail the methods you can use for the partial copy.

Array Copy and Buffer BlockCopy are methods that allow for a copy of a partial or subsection of the source array to the destination array. I will cover those methods in more detail in the rest of the article.

Summary Table

Analysis TypeArray CopyBuffer BlockCopy
Rank12
.NET Framework Version Available>= .NET 1.1>= .NET 1.1
Lines Of Code14
Speed Test158msN/A
Value Type Speed Test101ms103ms
LimitationsNoneOnly Value Types Supported

Array Copy Method

Array CopyTo Chart

Array Copy lets you copy a range of elements and lets you pick the starting point in the source array and the starting point to copy it to in the destination array. This is useful in case we need a method to do a partial copy. Since this method is a static method you don't need to create an array object to call this method.

There are a few requirements for Array Copy and you'll need to check these before you run your code.

The source and destination array must of the same dimension. This means that both must be either a one dimension, multidimensional, or jagged array type.. You can not have a one dimension array and copy part of it to a jagged array. You get a rank exception thrown.

The two arrays need to be compatible types. If the arrays are different types then Array Copy will try to cast copied source elements to the type of the destination. For example, if the source array was a type string and the destination was a type object. This would be compatible and it would succeed. But if the source array was type string and the destination was type double then this is a type mismatch. The array type mismatch exception would be thrown.

Lastly, if you do have two different types you can't go from a base type to a directive type. For example, you wouldn't be able to have the partial copy from a source array of type object and the destination array of type string since the string is derived from the object this would throw an invalid cast exception.

Array Copy Method Code Example

Array Copy Syntax

In the following example, I show that you can copy from indexes 1-2 and copy and paste them into another array. It can be any type and this work. That is why I have included a variety of types here. I'm able to write one method to handle each of the types by using generics. See example below.

Ideally, you'd want to add checks on the arrays to see if the length will work and not cause an exception. I have excluded it for the code to be concise.


//Create two different arrays of strings for different healthy lifestyles
string[] stringArraySource = new string[] { "Exercise regularly", "Eat a balanced diet", "Stay hydrated", "Get enough sleep", "Manage stress" };
string[] stringArrayDestination = new string[] { "", "", "", "","" };

//Create two different arrays of int 
int[] intArraySource = new int[] { 21, 63, 88, 1, 16 };
int[] intArrayDestination = new int[] { 0, 0, 0, 0 ,0};

//Create two different arrays of double
double[] doubleArraySource = new double[] { 14.51, 11.45, 67.57, 19.23, 0.1 };
double[] doubleArrayDestination = new double[] { 0, 0, 0, 0, 0 };

//Create two different arrays of bool
bool[] boolArraySource = new bool[] { true, false, false, true, false };
bool[] boolArrayDestination = new bool[] { false, false, false, false, false };

//Create two different arrays of float
float[] floatArraySource = new float[] { 2.05f, 32.62f, 3.45f, 16.7f, 0.54f };
float[] floatArrayDestination = new float[] { 0, 0, 0, 0,0 };

int sourceStartIndex = 1;
int destinationStartIndex = 1;
int copyLength = 2;

//Combined array method
CopyPartOfArrayAnotherArray<string>(stringArraySource, sourceStartIndex, stringArrayDestination, destinationStartIndex, copyLength);
CopyPartOfArrayAnotherArray<int>(intArraySource, sourceStartIndex, intArrayDestination, destinationStartIndex, copyLength);
CopyPartOfArrayAnotherArray<double>(doubleArraySource, sourceStartIndex, doubleArrayDestination, destinationStartIndex, copyLength);
CopyPartOfArrayAnotherArray<bool>(boolArraySource, sourceStartIndex, boolArrayDestination, destinationStartIndex, copyLength);
CopyPartOfArrayAnotherArray<float>(floatArraySource, sourceStartIndex, floatArrayDestination, destinationStartIndex, copyLength);

//Print out each array
PrintArray<string>(stringArrayDestination);
PrintArray<int>(intArrayDestination);
PrintArray<double>(doubleArrayDestination);
PrintArray<bool>(boolArrayDestination);
PrintArray<float>(floatArrayDestination);


void CopyPartOfArrayAnotherArray<T>(T[] arraySource, int sourceStartIndex, T[] arrayDestination, int destinationStartIndex, int copyLength)
{
    Array.Copy(arraySource, sourceStartIndex, arrayDestination, destinationStartIndex, copyLength);//Use Copy to partially copy part of the source array into the destination array 
}

void PrintArray<T>(T[] array)
{
    int index = 0;
    foreach (T item in array)//Loop through each item in the array
    {
        Console.WriteLine($"[{index++}] = {item}");//Print array item to the screen
    }
    Console.WriteLine();
    Console.WriteLine();
}
C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial
Array Copy Code Output
stringintdoubleboolfloat
[0] =[0] = 0[0] = 0[0] = False[0] = 0
[1] = Eat a balanced diet[1] = 63[1] = 11.45[1] = False[1] = 32.62
[2] = Stay hydrated[2] = 88[2] = 67.57[2] = False[2] = 3.45
[3] =[3] = 0[3] = 0[3] = False[3] = 0
[4] =[4] = 0[4] = 0[4] = False[4] = 0

Buffer BlockCopy Method

Copy Part Of Array Using Buffer Block Copy Chart

You can copy and paste part of an array to another using block copy but it does so for a chuck of bytes rather than indexes that an array normally uses. So block copy is a lower-level implementation as it copies the chunks of bytes.

This method uses several steps to convert indexes into bytes. So to get the indexes in terms of bytes we need to get the size of the element. For example, an int has a fixed size. In memory, the size of an int doesn't change no matter what the value is. So we can use the size of the method to get the size of int in bytes the multiply it by the number of indexes we want to copy from to get the index range in bytes.

The other consideration for this method is that it only works with value types. This means types that have a fixed size. It will not work with strings because it is a reference type and its size varies between strings and isn't a fixed size. The size of the method will not work on a string or any reference type. So you won't be able to use the classes that you write. This is a big disadvantage compared to array copy.

Let's look at an example.

Buffer BlockCopy Method Code Example

Copy Part Of Array Using Buffer Block Copy Syntax

This method takes up 4 lines. Most of which is just converting the starting values into terms of bytes. Once we have those then we apply it to the block copy method. The actual block copy method only takes up one line. We pass in the parameter very similar to the array copy method.

Again, I tried to show that this will work on a variety of types but also note that string is missing because it won't with strings.

//Create two different arrays of int 
int[] intArraySource = new int[] { 33, 66, 42, 36, 62 };
int[] intArrayDestination = new int[] { 0, 0, 0, 0, 0 };

//Create two different arrays of double
double[] doubleArraySource = new double[] { 2.95, 55.24, 20.55, 53.7, 41.53 };
double[] doubleArrayDestination = new double[] { 0, 0, 0, 0, 0 };

//Create two different arrays of bool
bool[] boolArraySource = new bool[] { true, false, true, true, false };
bool[] boolArrayDestination = new bool[] { false, false, false, false, false };

//Create two different arrays of float
float[] floatArraySource = new float[] { 41.88f, 1.95f, 59.23f, 19.93f, 5.21f };
float[] floatArrayDestination = new float[] { 0, 0, 0, 0, 0 };

int sourceStartIndex = 1;
int destinationStartIndex = 1;
int length = 2;

//Array Copy method

CopyPartOfIntArrayAnotherArray(intArraySource, sourceStartIndex, intArrayDestination, destinationStartIndex, length);
CopyPartOfDoubleArrayAnotherArray(doubleArraySource, sourceStartIndex, doubleArrayDestination, destinationStartIndex, length);
CopyPartOfBoolArrayAnotherArray(boolArraySource, sourceStartIndex, boolArrayDestination, destinationStartIndex, length);
CopyPartOfFloatArrayAnotherArray(floatArraySource, sourceStartIndex, floatArrayDestination, destinationStartIndex, length);



void CopyPartOfIntArrayAnotherArray(int[] arraySource, int sourceStartIndex, int[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(int);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(int);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(int);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}

void CopyPartOfDoubleArrayAnotherArray(double[] arraySource, int sourceStartIndex, double[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(double);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(double);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(double);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}
void CopyPartOfBoolArrayAnotherArray(bool[] arraySource, int sourceStartIndex, bool[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(bool);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(bool);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(bool);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}

void CopyPartOfFloatArrayAnotherArray(float[] arraySource, int sourceStartIndex, float[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(float);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(float);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(float);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}
Buffer BlockCopy Code Output
intdoubleboolfloat
[0] = 0[0] = 0[0] = False[0] = 0
[1] = 66[1] = 55.24[1] = False[1] = 1.95
[2] = 42[2] = 20.55[2] = True[2] = 59.23
[3] = 0[3] = 0[3] = False[3] = 0
[4] = 0[4] = 0[4] = False[4] = 0

Speed Test

This is a speed so that there can be some sort of comparison. There will be an average of 10 tests. Each test will call the function call 100 times. Each function call will have 5 million objects in the two arrays. There is a start index and copy of 100 thousand items from the source to the destination array.

Array Copy Speed Test Code

using System.Diagnostics;

int numberOfTests = 10;//Number of tests 
int numberOfFunctionCalls = 100;//Number of function calls made per test
int numberOfObjectsToCreate = 5000000;//Number test objects
int lengthOfRandomString = 50;
string testName = "Array Copy";//Test name to print to average
int startIndex = 100000;
int length = 100000;

void TestMethod(TestArrayDataContainer testArrayDataContainer)
{
    CopyPartOfArrayAnotherArray<string>(testArrayDataContainer.stringData1, startIndex, testArrayDataContainer.stringData2, startIndex, length);
    CopyPartOfArrayAnotherArray<int>(testArrayDataContainer.intData1, startIndex, testArrayDataContainer.intData2, startIndex, length);
    CopyPartOfArrayAnotherArray<double>(testArrayDataContainer.doubleData1, startIndex, testArrayDataContainer.doubleData2, startIndex, length);
    CopyPartOfArrayAnotherArray<bool>(testArrayDataContainer.boolData1, startIndex, testArrayDataContainer.boolData2, startIndex, length);
    CopyPartOfArrayAnotherArray<float>(testArrayDataContainer.floatArray1, startIndex, testArrayDataContainer.floatArray2, startIndex, length);
}

void CopyPartOfArrayAnotherArray<T>(T[] arraySource, int sourceStartIndex, T[] arrayDestination, int destinationStartIndex, int length)
{
    Array.Copy(arraySource, sourceStartIndex, arrayDestination, destinationStartIndex, length);//Use Copy to partially copy part of the source array into the destination array 
}
Array Copy Code Output
Test 1: 0m 0s 153ms
Test 2: 0m 0s 147ms
Test 3: 0m 0s 153ms
Test 4: 0m 0s 149ms
Test 5: 0m 0s 190ms
Test 6: 0m 0s 165ms
Test 7: 0m 0s 167ms
Test 8: 0m 0s 156ms
Test 9: 0m 0s 144ms
Test 10: 0m 0s 155ms
Array Copy Average Speed:158ms, In 10 Tests
Full Array Copy Test Code


using System.Diagnostics;

int numberOfTests = 10;//Number of tests 
int numberOfFunctionCalls = 100;//Number of function calls made per test
int numberOfObjectsToCreate = 10000000;//Number test objects
int lengthOfRandomString = 50;
string testName = "Array Copy";//Test name to print to average
int startIndex = 1000000;
int length = 1000000;



void TestMethod(TestArrayDataContainer testArrayDataContainer)
{
    CopyPartOfArrayAnotherArray<string>(testArrayDataContainer.stringData1, startIndex, testArrayDataContainer.stringData2, startIndex, length);
    CopyPartOfArrayAnotherArray<int>(testArrayDataContainer.intData1, startIndex, testArrayDataContainer.intData2, startIndex, length);
    CopyPartOfArrayAnotherArray<double>(testArrayDataContainer.doubleData1, startIndex, testArrayDataContainer.doubleData2, startIndex, length);
    CopyPartOfArrayAnotherArray<bool>(testArrayDataContainer.boolData1, startIndex, testArrayDataContainer.boolData2, startIndex, length);
    CopyPartOfArrayAnotherArray<float>(testArrayDataContainer.floatArray1, startIndex, testArrayDataContainer.floatArray2, startIndex, length);
}

void CopyPartOfArrayAnotherArray<T>(T[] arraySource, int sourceStartIndex, T[] arrayDestination, int destinationStartIndex, int length)
{
    Array.Copy(arraySource, sourceStartIndex, arrayDestination, destinationStartIndex, length);//Use copy to partially copy part of the source array into the destination array
}

List<double> testSpeedList = new List<double>();
for (int testIndex = 0; testIndex < numberOfTests; testIndex++)
{
    testSpeedList.Add(StartTest(testIndex));
}
Console.WriteLine($"{testName} Average Speed:{Math.Round(testSpeedList.Average())}ms, In {numberOfTests} Tests");

double StartTest(int testIndex)
{
    Stopwatch stopwatch = new Stopwatch();
    string[] testStringData1 = GetStringArrayData();//Generate a random array of strings
    string[] testStringData2 = GetStringArrayData();//Generate a random array of strings
    int[] testIntData1 = GetIntArrayData();//Generate a random array of ints
    int[] testIntData2 = GetIntArrayData();//Generate a random array of ints
    double[] testDoubleData1 = GetDoubleArrayData();//Generate a random array of double
    double[] testDoubleData2 = GetDoubleArrayData();//Generate a random array of double
    bool[] testBoolData1 = GetBoolArrayData();//Generate a random array of bool
    bool[] testBoolData2 = GetBoolArrayData();//Generate a random array of bool
    float[] testFloatData1 = GetFloatArrayData();//Generate a random array of float
    float[] testFloatData2 = GetFloatArrayData();//Generate a random array of float
    TestArrayDataContainer testArrayDataContainer = new TestArrayDataContainer(testStringData1, testStringData2, testIntData1, testIntData2, testDoubleData1, testDoubleData2, testBoolData1, testBoolData2, testFloatData1, testFloatData2);
    for (int i = 0; i < numberOfFunctionCalls; i++)
    {
        stopwatch.Start();//Start the Stopwatch timer
        TestMethod(testArrayDataContainer);//
        stopwatch.Stop();//Stop the Stopwatch timer
    }
    stopwatch.Stop();//Stop the Stopwatch timer
    Console.WriteLine($"Test {testIndex + 1}: {stopwatch.Elapsed.Minutes}m {stopwatch.Elapsed.Seconds}s {stopwatch.Elapsed.Milliseconds}ms");
    return stopwatch.Elapsed.TotalMilliseconds;
}

string[] GetStringArrayData()
{
    string[] testData = new string[numberOfObjectsToCreate];
    for (int i = 0; i < numberOfObjectsToCreate; i++)
    {
        string value = GenerateRandomString(lengthOfRandomString);
        testData[i] = value;
    }
    return testData;
}

int[] GetIntArrayData()
{
    Random random = new Random();
    int[] testData = new int[numberOfObjectsToCreate];
    for (int i = 0; i < numberOfObjectsToCreate; i++)
    {
        testData[i] = random.Next(0, numberOfObjectsToCreate);
    }
    return testData;
}

double[] GetDoubleArrayData()
{
    Random random = new Random();
    double[] testData = new double[numberOfObjectsToCreate];
    for (int i = 0; i < numberOfObjectsToCreate; i++)
    {
        testData[i] = random.NextDouble();
    }
    return testData;
}

bool[] GetBoolArrayData()
{
    Random random = new Random();
    bool[] testData = new bool[numberOfObjectsToCreate];
    for (int i = 0; i < numberOfObjectsToCreate; i++)
    {
        testData[i] = (random.Next(0, 1) == 1 ? true : false);
    }
    return testData;
}

float[] GetFloatArrayData()
{
    Random random = new Random();
    float[] testData = new float[numberOfObjectsToCreate];
    for (int i = 0; i < numberOfObjectsToCreate; i++)
    {
        testData[i] = random.NextSingle();
    }
    return testData;
}
string GenerateRandomString(int length)
{
    Random random = new Random();
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    return new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}
class TestArrayDataContainer
{
    public string[] stringData1;
    public string[] stringData2;

    public int[] intData1;
    public int[] intData2;

    public double[] doubleData1;
    public double[] doubleData2;

    public bool[] boolData1;
    public bool[] boolData2;

    public float[] floatArray1;
    public float[] floatArray2;

    public TestArrayDataContainer(string[] stringData1, string[] stringData2, int[] intData1, int[] intData2, double[] doubleData1, double[] doubleData2, bool[] boolData1, bool[] boolData2, float[] floatArray1, float[] floatArray2)
    {
        this.stringData1 = stringData1;
        this.stringData2 = stringData2;
        this.intData1 = intData1;
        this.intData2 = intData2;
        this.doubleData1 = doubleData1;
        this.doubleData2 = doubleData2;
        this.boolData1 = boolData1;
        this.boolData2 = boolData2;
        this.floatArray1 = floatArray1;
        this.floatArray2 = floatArray2;
    }
}

Value Speed Test

This will be the same test as before except that the string is removed so that it can be compared to the block copy method.

Array Copy Speed Test Code

void TestMethod(TestArrayDataContainer testArrayDataContainer)
{
    CopyPartOfArrayAnotherArray<int>(testArrayDataContainer.intData1, startIndex, testArrayDataContainer.intData2, startIndex, length);
    CopyPartOfArrayAnotherArray<double>(testArrayDataContainer.doubleData1, startIndex, testArrayDataContainer.doubleData2, startIndex, length);
    CopyPartOfArrayAnotherArray<bool>(testArrayDataContainer.boolData1, startIndex, testArrayDataContainer.boolData2, startIndex, length);
    CopyPartOfArrayAnotherArray<float>(testArrayDataContainer.floatArray1, startIndex, testArrayDataContainer.floatArray2, startIndex, length);
}

void CopyPartOfArrayAnotherArray<T>(T[] arraySource, int sourceStartIndex, T[] arrayDestination, int destinationStartIndex, int length)
{
    Array.Copy(arraySource, sourceStartIndex, arrayDestination, destinationStartIndex, length);//Use copy to partial copy part of the source array into the destination array
}

Buffer BlockCopy Speed Test Code


void CopyPartOfIntArrayAnotherArray(int[] arraySource, int sourceStartIndex, int[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(int);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(int);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(int);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}

void CopyPartOfDoubleArrayAnotherArray(double[] arraySource, int sourceStartIndex, double[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(double);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(double);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(double);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}
void CopyPartOfBoolArrayAnotherArray(bool[] arraySource, int sourceStartIndex, bool[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(bool);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(bool);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(bool);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}

void CopyPartOfFloatArrayAnotherArray(float[] arraySource, int sourceStartIndex, float[] arrayDestination, int destinationStartIndex, int length)
{
    int copyLength = length * sizeof(float);//Get the length of the part to copy by the number of bytes
    int sourceStartIndexInBytes = sourceStartIndex * sizeof(float);
    int destinationStartIndexInBytes = destinationStartIndex * sizeof(float);

    Buffer.BlockCopy(arraySource, sourceStartIndexInBytes, arrayDestination, destinationStartIndexInBytes, copyLength);//Copy part of array to destination array
}
Array Copy Code Output
Test 1: 0m 0s 115ms
Test 2: 0m 0s 99ms
Test 3: 0m 0s 98ms
Test 4: 0m 0s 98ms
Test 5: 0m 0s 100ms
Test 6: 0m 0s 99ms
Test 7: 0m 0s 99ms
Test 8: 0m 0s 100ms
Test 9: 0m 0s 100ms
Test 10: 0m 0s 102ms
Value Array Copy Average Speed:101ms, In 10 Tests
Buffer BlockCopy Code Output
Test 1: 0m 0s 110ms
Test 2: 0m 0s 103ms
Test 3: 0m 0s 104ms
Test 4: 0m 0s 104ms
Test 5: 0m 0s 102ms
Test 6: 0m 0s 98ms
Test 7: 0m 0s 101ms
Test 8: 0m 0s 102ms
Test 9: 0m 0s 104ms
Test 10: 0m 0s 100ms
Buffer BlockCopy Average Speed:103ms, In 10 Tests

Conclusion

The best method for copying and pasting part of an array to another array is Array Copy. Array Copy is a one-liner and still just a buffer block copy. Array Copy has no limitation and has been around a long time since .NET 1.1 so it will be in your code base. Even though in the second test of value types Array Copy and Buffer BlockCopy are essentially the same. Block copy doesn't support reference types and so I can't recommend it for this use case.

Know any other ways to copy part of an array to another array? Let me know in the comments below.

Get Latest Updates