Skip to content

Commit

Permalink
[util-core] Avoid unnecessary allocations in ByteArray.extract
Browse files Browse the repository at this point in the history
Unapply in pattern matching creates a tuple and unnecessarily boxes integers. Rewriting it in a more imperative style for efficiency.

Differential Revision: https://phabricator.twitter.biz/D1173579
  • Loading branch information
mbezoyan authored and jenkins committed Sep 30, 2024
1 parent 8700f19 commit b5bc478
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions util-core/src/main/scala/com/twitter/io/Buf.scala
Original file line number Diff line number Diff line change
Expand Up @@ -778,13 +778,15 @@ object Buf {
*
* A copy may be performed if necessary.
*/
def extract(buf: Buf): Array[Byte] = Buf.ByteArray.coerce(buf) match {
case Buf.ByteArray.Owned(bytes, 0, end) if end == bytes.length =>
bytes
case Buf.ByteArray.Shared(bytes) =>
def extract(buf: Buf): Array[Byte] = {
val byteArray = Buf.ByteArray.coerce(buf)
if (byteArray.begin == 0 && byteArray.end == byteArray.bytes.length) {
byteArray.bytes
} else {
// If the unsafe version included offsets, we need to create a new array
// containing only the relevant bytes.
bytes
byteArray.copiedByteArray
}
}
}

Expand Down

0 comments on commit b5bc478

Please sign in to comment.