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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For primitive types (including bytes), use
System.Buffer.BlockCopyinstead 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.BlockCopysolution 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.