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:
<code class="language-csharp">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 }));</code>
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.
The above is the detailed content of How Can I Optimize Array Concatenation in C# for Better Performance?. For more information, please follow other related articles on the PHP Chinese website!