Bytearray - Append Two or More Byte Arrays in C# - Stack Overflow
Bytearray - Append Two or More Byte Arrays in C# - Stack Overflow
xDismiss
JointheStackOverflowCommunity
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:
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:
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:
...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
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