Created
February 4, 2025 08:38
-
-
Save takapi327/233176b326b8019e55bf6bb1c289987c to your computer and use it in GitHub Desktop.
Regarding scodec performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//> using scala 3.6.3 | |
//> using dep org.scodec::scodec-bits:1.2.1 | |
//> using dep org.scodec::scodec-core:2.3.2 | |
import scodec.bits.* | |
import scodec.codecs.* | |
val iterations = 10000 | |
val str = "Hello World!" | |
val lengthBits = BitVector(str.length) | |
val stringBits = BitVector.encodeUtf8(str).toOption.get // Not safe, but only used for verification. | |
val bits = lengthBits ++ stringBits | |
// warm up | |
for (i <- 0 until 10000) { | |
decodeByCodecs() | |
decodeBySplitAt() | |
} | |
val benchmark1Start = System.nanoTime() | |
for (i <- 0 until iterations) { | |
decodeByCodecs() | |
} | |
val benchmark1End = System.nanoTime() - benchmark1Start | |
val benchmark2Start = System.nanoTime() | |
for (i <- 0 until iterations) { | |
decodeBySplitAt() | |
} | |
val benchmark2End = System.nanoTime() - benchmark2Start | |
println(s"benchmark1: ${benchmark1End / 1000000} ms") // 5 ms | |
println(s"benchmark2: ${benchmark2End / 1000000} ms") // 2 ms | |
def decodeByCodecs(): String = | |
(for | |
length <- uint8 | |
str <- bytes(length) | |
yield new String(str.toArray, "UTF-8")).decode(bits).require.value | |
def decodeBySplitAt(): String = | |
val (lengthBits, postLengthBits) = bits.splitAt(8) | |
val length = lengthBits.toInt(false) | |
val strBits = postLengthBits.take(length * 8L) | |
new String(strBits.toByteArray, "UTF-8") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also verified the process when using Array and Chunk.
The results were as follows, with the direct decoding of Chunk being the fastest.
Full code