iex
04/01/2020, 8:08 PMfold
is less performant than a loop, right?
Specifically:
bytes.fold("") { acc, byte -> acc + String.format("%02X", byte) }
vs
var ret: String = ""
for (b in bytes) {
ret += String.format("%02X", b)
}
return ret
jw
04/01/2020, 8:12 PMbuildString
, 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.jw
04/01/2020, 8:13 PMfold
and the loop are basically equivalent. If you CMD+B into the source of fold
you'll just find a loop.iex
04/01/2020, 8:19 PMprivate 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)
}
iex
04/01/2020, 8:20 PMiex
04/01/2020, 8:20 PMfold
is a loop now, thanks 👍jw
04/01/2020, 8:25 PM