From b5bc478a38b045c4616f38231a69ce90e8aff044 Mon Sep 17 00:00:00 2001 From: Mikhail Bezoyan Date: Mon, 30 Sep 2024 08:29:16 +0000 Subject: [PATCH] [util-core] Avoid unnecessary allocations in ByteArray.extract 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 --- util-core/src/main/scala/com/twitter/io/Buf.scala | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/util-core/src/main/scala/com/twitter/io/Buf.scala b/util-core/src/main/scala/com/twitter/io/Buf.scala index f942c6b09d..051de125da 100644 --- a/util-core/src/main/scala/com/twitter/io/Buf.scala +++ b/util-core/src/main/scala/com/twitter/io/Buf.scala @@ -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 + } } }