What is the most efficient way to combine two ByteArray instances?

I want to join two ByteArray instances in Squeak, Cuis or Pharo Smalltalk

b := #[10 11 12 13] asOrderedCollection.
b addAll: #[21 22 23 24].
b asByteArray

      

Are there any more efficient ways to do this?

+3


source to share


2 answers


Would concatenation be better ...?



#[10 11 12 13],#[21 22 23 24 ]

      

+8


source


Yes. Using OrderedCollection will involve several unnecessary object allocations and redundant copying. You have to create a new byte array and copy the contents of the original arrays into it:

a := #[10 11 12 13].
b := #[21 22 23 24].
c := ByteArray new: (a size + b size).
c replaceFrom: 1 to: a size with: a startingAt: 1.
c replaceFrom: a size + 1 to: c size with: b startingAt: 1.

      



This only allocates a new ByteArray and does copy using primitives, so it's pretty fast. He will work for Squeak, Cuis and Pharo, and most likely other Smalltalks.

+3


source







All Articles