-2

I have two byte arrays. I want to merge these two byte arrays into one byte array.

Usually, I just create a new byte array with length = byte array #1 + byte array #2. Then copy byte array #1 and #2 to the new byte array.

Is there a more efficient way to merge two byte arrays using VB.NET and .NET 4?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nano White
  • 55
  • 1
  • 1
  • 3
  • 7
    Can you post your code? There are _many ways_ to copy the two arrays, we won't know if you're doing it efficiently until we see you code. – Binary Worrier Sep 20 '11 at 08:14
  • Eh, my explanation is clear enough – Nano White Sep 20 '11 at 08:15
  • 6
    @NanoWhite, To me it seems you have a poor attitude towards people who are willing to help you and blaming them for your poor attitude. In fact, like the way you are behaving now Id rather not have you in the SO community, we were all willing to help you but all you have is a awful way of treating us. – Stormenet Sep 20 '11 at 08:58
  • 3
    Obviously, your explanation _was not_ clear enough. Please don't do this again. Locking due to the noise I found in the history. **Note** Many comments have been removed from this question. – Tim Post Sep 20 '11 at 10:09
  • https://stackoverflow.com/questions/415291/best-way-to-combine-two-or-more-byte-arrays-in-c-sharp/45351646#45351646 – ARC Jul 27 '17 at 13:07

2 Answers2

12

Your existing approach is the most efficient (for what I think is the commonly understood meaning of "efficient") as long as it is implemented properly.

The implementation should look like this:

var merged = new byte[array1.Length + array2.Length];
array1.CopyTo(merged, 0);
array2.CopyTo(merged, array1.Length);
Jon
  • 428,835
  • 81
  • 738
  • 806
  • [An answer to the duplicate-related claims](http://stackoverflow.com/questions/415291/best-way-to-combine-two-or-more-byte-arrays-in-c-sharp/415396#415396) System.Buffer.BlockCopy is faster (for byte). – Peter Mortensen Feb 08 '17 at 13:58
9

In our Tcpclient we like to use Buffer.BlockCopy instead of array.copy.

See this question for more info: Array.Copy vs Buffer.BlockCopy
And this one for hard numbers: Best way to combine two or more byte arrays in C#

Community
  • 1
  • 1
Stormenet
  • 25,926
  • 9
  • 53
  • 65