From d52440d30c5fbe39024e83d265a7ac32d522c9a8 Mon Sep 17 00:00:00 2001 From: Martin Brehovsky <63611096+martin-dd@users.noreply.github.com> Date: Thu, 19 Dec 2024 14:39:52 -0800 Subject: [PATCH] fix: optimizations reducing heap usage in MsgPackDataOutputBuffer --- .../stream/MsgPackDataBuffer.kt | 29 +++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt index aef7b15..aaf6c7e 100644 --- a/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt +++ b/serialization-msgpack/src/commonMain/kotlin/com.ensarsarajcic.kotlinx.serialization.msgpack/stream/MsgPackDataBuffer.kt @@ -5,15 +5,34 @@ interface MsgPackDataBuffer { } class MsgPackDataOutputBuffer() : MsgPackDataBuffer { - private val bytes = mutableListOf() + private val byteArrays = mutableListOf() - fun add(byte: Byte) = bytes.add(byte) + fun add(byte: Byte) { + byteArrays.add(ByteArray(1) { byte }) + } - fun addAll(bytes: List) = this.bytes.addAll(bytes) + fun addAll(bytes: List) { + if (bytes.isNotEmpty()) { + byteArrays.add(bytes.toByteArray()) + } + } - fun addAll(bytes: ByteArray) = this.bytes.addAll(bytes.toList()) + fun addAll(bytes: ByteArray) { + if (bytes.isNotEmpty()) { + byteArrays.add(bytes) + } + } - override fun toByteArray() = bytes.toByteArray() + override fun toByteArray(): ByteArray { + val totalSize = byteArrays.sumOf { it.size } + val outputArray = ByteArray(totalSize) + var currentIndex = 0 + byteArrays.forEach { + it.copyInto(outputArray, currentIndex) + currentIndex += it.size + } + return outputArray + } } class MsgPackDataInputBuffer(private val byteArray: ByteArray) : MsgPackDataBuffer {