I have 3 byte arrays in C# that I need to combine into one. What would be the most efficient method to complete this task?
C# – Best way to combine two or more byte arrays in C#
arraysc++
Related Question
- Java – Create ArrayList from array
- Javascript – How to check if an array includes a value in JavaScript
- C# – Case insensitive ‘Contains(string)’
- Javascript – Sort array of objects by string property value
- Javascript – How to merge two arrays in JavaScript and de-duplicate items
- Javascript – How to add new array elements at the beginning of an array in Javascript
- Javascript – Merge/flatten an array of arrays
Best Solution
For primitive types (including bytes), use
System.Buffer.BlockCopy
instead ofSystem.Array.Copy
. It's faster.I timed each of the suggested methods in a loop executed 1 million times using 3 arrays of 10 bytes each. Here are the results:
System.Array.Copy
- 0.2187556 secondsSystem.Buffer.BlockCopy
- 0.1406286 secondsI increased the size of each array to 100 elements and re-ran the test:
System.Array.Copy
- 0.2812554 secondsSystem.Buffer.BlockCopy
- 0.2500048 secondsI increased the size of each array to 1000 elements and re-ran the test:
System.Array.Copy
- 1.0781457 secondsSystem.Buffer.BlockCopy
- 1.0156445 secondsFinally, I increased the size of each array to 1 million elements and re-ran the test, executing each loop only 4000 times:
System.Array.Copy
- 13.4533833 secondsSystem.Buffer.BlockCopy
- 13.1096267 secondsSo, if you need a new byte array, use
But, if you can use an
IEnumerable<byte>
, DEFINITELY prefer LINQ's Concat<> method. It's only slightly slower than the C# yield operator, but is more concise and more elegant.If you have an arbitrary number of arrays and are using .NET 3.5, you can make the
System.Buffer.BlockCopy
solution more generic like this:*Note: The above block requires you adding the following namespace at the the top for it to work.
To Jon Skeet's point regarding iteration of the subsequent data structures (byte array vs. IEnumerable<byte>), I re-ran the last timing test (1 million elements, 4000 iterations), adding a loop that iterates over the full array with each pass:
System.Array.Copy
- 78.20550510 secondsSystem.Buffer.BlockCopy
- 77.89261900 secondsThe point is, it is VERY important to understand the efficiency of both the creation and the usage of the resulting data structure. Simply focusing on the efficiency of the creation may overlook the inefficiency associated with the usage. Kudos, Jon.