Home >Backend Development >C++ >How Can I Efficiently Concatenate Arrays in C#?

How Can I Efficiently Concatenate Arrays in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-17 06:47:10185browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn