"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Optimize Array Concatenation in C# for Better Performance?

How Can I Optimize Array Concatenation in C# for Better Performance?

Posted on 2025-03-04
Browse:726

How Can I Optimize Array Concatenation in C# for Better Performance?

Boosting C# Array Concatenation Performance: A Superior Alternative to Concat

C#'s Concat method provides a simple solution for joining arrays. However, its performance can be suboptimal when dealing with large arrays. For significantly improved efficiency in array concatenation, consider this alternative:

int[] x = new int[] { 1, 2, 3 };
int[] y = new int[] { 4, 5 };

int[] z = new int[x.Length   y.Length];
Array.Copy(x, z, x.Length);
Array.Copy(y, 0, z, x.Length, y.Length);

Debug.Assert(z.SequenceEqual(new int[] { 1, 2, 3, 4, 5 }));

This method directly allocates a new array z of sufficient size to hold both x and y. It then leverages Array.Copy to efficiently transfer the elements of x and y into z. This avoids the creation of intermediate arrays, leading to faster execution, especially with larger datasets.

Important Consideration: While Concat remains suitable for smaller arrays where performance isn't critical, the approach above offers a substantial performance advantage for scenarios involving large arrays.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3