0% found this document useful (0 votes)
1K views3 pages

Bytearray - Append Two or More Byte Arrays in C# - Stack Overflow

The document discusses different ways to concatenate or append two or more byte arrays in C# for .NET 2.0. It describes methods like using BlockCopy, MemoryStream, a for loop, LINQ, and List. It provides code examples and results from performance tests of each approach.

Uploaded by

nothzin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views3 pages

Bytearray - Append Two or More Byte Arrays in C# - Stack Overflow

The document discusses different ways to concatenate or append two or more byte arrays in C# for .NET 2.0. It describes methods like using BlockCopy, MemoryStream, a for loop, LINQ, and List. It provides code examples and results from performance tests of each approach.

Uploaded by

nothzin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

6/12/2016 bytearray - Append two or more byte arrays in C# - Stack Overow

signup login tour help

xDismiss

JointheStackOverflowCommunity

Stack Overflow is a community of 6.4 million


programmers, just like you, helping each other.
Join them it only takes a minute:

Signup

AppendtwoormorebytearraysinC#

Isthereabest(seebelow)waytoappendtwobytearraysinC#?

PretendingIhavecompletecontrol,Icanmakethefirstbytearraysufficientlylargetoholdthesecondbytearrayattheendandusethe
Array.CopyTofunction.OrIcanloopoverindividualbytesandmakeanassignment.

Aretherebetterways?Ican'timaginedoingsomethinglikeconvertingthebytearraystostringandjoiningthemandconvertingthemback
wouldbebetterthaneithermethodabove.

Intermsofbest/better(inorder):

1.Fastest
2.LeastRAMconsumption

AconstraintisthatImustworkinthe.NET2.0framework.

ThetwochoicesrecommendedareMemoryStreamandBlockCopy.Ihaverunasimplespeedtestof10,000,000loops3timesandgotthe
followingresults:

Averageof3runsof10,000,000loopsinmilliseconds:

BlockCopyTime:1154,witharangeof13milliseconds
MemoryStreamGetBufferTime:1470,witharangeof14milliseconds
MemoryStreamToArrayTime:1895,witharangeof3milliseconds
CopyToTime:2079,witharangeof19milliseconds
BytebybyteTime:2203,witharangeof10milliseconds

ResultsofList<byte>AddRangeover10millionloops:List<byte>Time:16694

RelativeRAMConsumption(1isbaseline,higherisworse):

Bytebybyte:1
BlockCopy:1
CopyTo:1
MemoryStreamGetBuffer:2.3
MemoryStreamToArray:3.3
List<byte>:4.2

Thetestshowsthatingeneral,unlessyouaredoingalotofbytecopies[whichIam],lookingatbytecopiesisnotworthafocus[e.g.10
millionrunsyieldingadifferenceofasmuchas1.1seconds].

c# bytearray

editedApr27at14:54 askedMay21'09at20:58
PeterMortensen torial
10.4k 13 72 108 10.5k 9 52 81

http://stackoverow.com/questions/895120/append-two-or-more-byte-arrays-in-c-sharp 1/3
6/12/2016 bytearray - Append two or more byte arrays in C# - Stack Overow
Re:MemoryusageThebestwaytofindthatistouseamemoryprofiler.dss539May22'09at15:19

Thanks,IusedtheCLRProfilertogetthememorydata.Forgottohaveitrunasadministrator,sogetting
resultsforthatwasdelayed. torial May22'09at21:08

possibleduplicateofBestwaytocombinetwoormorebytearraysinC#FraserJul29'13at22:32

8Answers

YouwantBlockCopy

AccordingtothisblogpostitisfasterthanArray.CopyTo.

answeredMay21'09at21:11
dss539
4,304 1 19 48

1 yeahArray.CopyToisO(n).It'sunfortunatethatMSdidn'toptimizethisatallforbytearrays...
JonathanCDickinsonMay22'09at6:17

BlockCopybeatMemoryStreaminspeed(don'thaveareliabletestforRAM),soselectingasanswer.
torial May22'09at15:38

CreateanewMemoryStreampassingintotheconstructorabufferthat'sexactlythesizeofthe
mergedone.Writetheindividualarrays,andthenfinallyusethebuffer:

byte[] deadBeef = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF};


byte[] baadF00d = new byte[] { 0xBA, 0xAD, 0xF0, 0x0D};
int newSize = deadBeef.Length + baadF00d.Length;
var ms = new MemoryStream(new byte[newSize], 0, newSize, true, true);
ms.Write(deadBeef, 0, deadBeef.Length);
ms.Write(baadF00d, 0, baadF00d.Length);
byte[] merged = ms.GetBuffer();

AlotofthelowlevelI/Ofunctionsin.NETtakebytearraysandoffsets.Thiswasdoneto
preventneedlesscopies.Besureyoureallyneedthemergedarrayifthisisperformance
sensitive,otherwisejustusebuffersandoffsets.

answeredMay21'09at21:18
JeffMoser
14.8k 3 48 75

Ifyougothisroute,usems.ToArray()ratherthanms.GetBuffer()eventhoughyou'repassingtheexplicit
length,it'sstillpossiblethattheinternalbufferreturnedviaGetBuffer()willhavemorebytesthanspecified.
Thatistosay:don'trelyontheinternalimplementationofMemoryStream.ErikForbesMay21'09at
21:20

1 ToArraywillcreateacopywhichwillhurtperformance.Ifyougothisroutewithanexplicitbuffersize,it'llbe
exactlythesizeyouspecified.Ifyoutrytogolarger,you'llgetaNotSupportedException.JeffMoserMay
21'09at21:24

YoucouldalsouseanapproachwithaMemoryStream.Supposeb1andb2aretwobyte
arrays,youcangetanewone,b3,byusingtheMemoryStreaminthefollowingfashion:

var s = new MemoryStream();


s.Write(b1, 0, b1.Length);
s.Write(b2, 0, b2.Length);
var b3 = s.ToArray();

ThisshouldworkwithoutLINQandisinfactquiteabitfaster.

answeredMay21'09at21:29
flq
15.4k 3 36 64

Ilikethatthisisquiteabitsmallerincode.Easiertounderstandmaybe.Clean:)Cort3zJan21'13at
11:13

http://stackoverow.com/questions/895120/append-two-or-more-byte-arrays-in-c-sharp 2/3
6/12/2016 bytearray - Append two or more byte arrays in C# - Stack Overow

Anotheroption,althoughIhaven'ttestedittoseehowitfaresintermsofspeedandmemory
consumption,wouldtheLINQapproach:

byte[] combined = bytesOne.Concat(bytesTwo).Concat(bytesThree).ToArray();

...wherebytesOne,bytesTwo,andbytesThreearebytearrays.SinceConcatusesdeferred
execution,thisshouldn'tcreateanyintermediatearrays,anditshouldn'tduplicatetheoriginal
arraysuntilitconstructsthefinalmergedarrayattheend.

Edit:LINQBridgewillallowyoutouseLINQtoObjects(whichthisisanexampleof)inthe2.0
framework.Iunderstandifyoudon'twanttodependonthis,butit'sanoption.

answeredMay21'09at21:11
JoelMueller
20.3k 7 47 76

Thanks,Iamunfortunatelylimitedto2.0.Ihaveupdatedmyquestiontostatethat. torial May21'09at


21:13

Ifyouhavearrayswherethesizewillchangefromtimetotime,you'reprobablybetteroffusing
a List<T> inthefirstplace.Thenyoucanjustcallthe AddRange() methodofthelist.

Otherwise,Array.Copy()orArray.CopyTo()areasgoodasanythingelseyou'relikelytosee.

answeredMay21'09at21:05
JoelCoehoorn
252k 92 446 666

HaveyoutaughtaboutusingListorArrayListinsteadofanArray?Withthesetypestheycan
groworshrinkandappendviaInsertRange

answeredMay21'09at21:13
AndrewB
654 1 7 17

Doyouneedtheoutputtoactuallybeabytearray?

Ifnot,youcouldcreateyourselfa"smartcursor"(whichissimilartowhatLINQdoes):Createa
customIEnumerator<byte>thatwillfirstiteratethefirstarray,andjustcontinueonthesecond
onewithoutinteruption.

Thiswouldworkinthe2.0frameworkbefast(inthatthejoiningofarrayshasvirtuallynocost),
andusenomoreRAMthanthearraysalreadyconsume.

answeredMay21'09at21:22
ArjanEinbu
10.1k 37 55

Yourfirstoptionofmakingthefirstarraylargeenoughtocontainthesecondarrayandusing
Array.CopyToendsupbeingroughlythesameasmanuallyiteratingovereachitemand
makingtheassignment.Array.CopyTo()justmakesitmoreconcise.

Convertingtostringandbacktoarraywillbehorriblyslowincontrasttotheabove.Andwould
likelyusemorememory.

answeredMay21'09at21:03
Nate
18.6k 14 79 153

http://stackoverow.com/questions/895120/append-two-or-more-byte-arrays-in-c-sharp 3/3

You might also like