Hi folks, `fold` is less performant than a loop, r...
# announcements
i
Hi folks,
fold
is less performant than a loop, right? Specifically:
Copy code
bytes.fold("") { acc, byte -> acc + String.format("%02X", byte) }
vs
Copy code
var ret: String = ""
for (b in bytes) {
    ret += String.format("%02X", b)
}
return ret
j
Both of those are going to be pretty horrific because of what you're doing with the string. Wrap it all in
buildString
, presize with
bytes.length * 2
, and append in a loop. You probably also want to avoid doing
String.format
and encode the bytes directly to chars which is must faster and doesn't allocate.
But otherwise
fold
and the loop are basically equivalent. If you CMD+B into the source of
fold
you'll just find a loop.
i
I found this in SO:
Copy code
private val HEX_ARRAY = "0123456789ABCDEF".toCharArray()
fun ByteArray.toHex(): String {
    val hexChars = CharArray(size * 2)
    for (j in indices) {
        val v: Int = this[j].toInt() and 0xFF
        hexChars[j * 2] = HEX_ARRAY[v ushr 4]
        hexChars[j * 2 + 1] = HEX_ARRAY[v and 0x0F]
    }
    return String(hexChars)
}
that's what you mean, right?
and I see
fold
is a loop now, thanks 👍
j
Yes something like that will be much more performant!
👍 1