Home >Backend Development >C++ >How Can I Efficiently Concatenate Arrays in C#?
Optimizing Array Concatenation in C#
Combining arrays in C# is a common task. The Concat
method offers a simple solution:
<code class="language-csharp">int[] x = { 1, 2, 3 }; int[] y = { 4, 5 }; int[] z = x.Concat(y).ToArray(); Debug.Assert(z.SequenceEqual(new int[] { 1, 2, 3, 4, 5 }));</code>
However, Concat
's performance degrades noticeably with larger arrays (as discussed in "Array Concatenation in C#," performance significantly decreases beyond 10,000 elements).
A Higher-Performance Alternative
For improved efficiency, especially with substantial arrays, a manual approach offers a significant advantage. This involves creating a new array of the correct size and directly copying elements:
<code class="language-csharp">var z = new int[x.Length + y.Length]; x.CopyTo(z, 0); y.CopyTo(z, x.Length);</code>
This method avoids the overhead inherent in Concat
, resulting in faster concatenation, particularly for large datasets. While slightly more verbose, the performance gains make it a preferable choice for larger-scale array manipulation.
The above is the detailed content of How Can I Efficiently Concatenate Arrays in C#?. For more information, please follow other related articles on the PHP Chinese website!