```import kotlin.math.PI import kotlin.system.meas...
# getting-started
v
Copy code
import kotlin.math.PI
import kotlin.system.measureTimeMillis

fun test1(a : FloatArray) : Float {
    val angles = a.map { it.toDegrees() }
    val yaw = angles[0]
    val pitch = angles[1]
    return yaw + pitch
}

fun test2(angles : FloatArray) : Float {
    val yaw = angles[0].toDegrees()
    val pitch = angles[1].toDegrees()
    return yaw + pitch
}

fun Float.toDegrees() : Float {
    return (this * 180 / PI).toFloat()
}


fun main(args: Array<String>) {
    val a = floatArrayOf(0.5f, 0.7f)

    val test2Time = measureTimeMillis {
        var out = 0L
        for (i in 0..1000000) {
            out += test2(a).toLong()
        }
    }
    val test1Time = measureTimeMillis {
        var out = 0L
        for (i in 0..1000000) {
            out += test1(a).toLong()
        }
    }
    println("Test1: $test1Time ms")
    println("Test2: $test2Time ms")
}
Test1: 42 ms Test2: 7 ms Using map is pretty costy. Am i doing something wrong?
s
It allocates a new list, which might account for some of the difference. The timings you got might also not be a good reflection of reality, because microbenchmarking is hard.
v
This comes from a real use case, that was profiled in android studio. This is how we found that this map is expensive.
👍 1
e
map use List which requires allocation on the heap of as well as boxing all the Float elements, whereas the second is completely on stack with primitives, and the computation is pretty minimal, so it's unsurprising that the overhead dominates
1
s
👍blob think smart I forgot about the boxing 😄
461 Views