Skip to content

Commit b5bc478

Browse files
mbezoyanjenkins
authored andcommitted
[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
1 parent 8700f19 commit b5bc478

File tree

1 file changed

+7
-5
lines changed
  • util-core/src/main/scala/com/twitter/io

1 file changed

+7
-5
lines changed

util-core/src/main/scala/com/twitter/io/Buf.scala

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -778,13 +778,15 @@ object Buf {
778778
*
779779
* A copy may be performed if necessary.
780780
*/
781-
def extract(buf: Buf): Array[Byte] = Buf.ByteArray.coerce(buf) match {
782-
case Buf.ByteArray.Owned(bytes, 0, end) if end == bytes.length =>
783-
bytes
784-
case Buf.ByteArray.Shared(bytes) =>
781+
def extract(buf: Buf): Array[Byte] = {
782+
val byteArray = Buf.ByteArray.coerce(buf)
783+
if (byteArray.begin == 0 && byteArray.end == byteArray.bytes.length) {
784+
byteArray.bytes
785+
} else {
785786
// If the unsafe version included offsets, we need to create a new array
786787
// containing only the relevant bytes.
787-
bytes
788+
byteArray.copiedByteArray
789+
}
788790
}
789791
}
790792

0 commit comments

Comments
 (0)