I was measuring the performance of inline functions when I encountered this really weird behavior.
fun normalFunction(block: () -> Unit) = block()
inline fun inlineFunction(block: () -> Unit) = block()
The following piece of code produces the output 0.315988524
.
var x = 0
println(measureNanoTime {
repeat(1_000_000_000) {
normalFunction {
x += it
}
}
} / 1E9)
Replacing normalFunction
by inlineFunction
produces the output 0.307185642
; slightly faster as one might expect.
Now to the weird part. If I run both pieces of code directly in the same function (renaming x
to y
in one instance or encapsulating both blocks with run { ... }
) then the produced output varies drastically depending on which block is run first:
normalFunction
theninlineFunction
produces the output0.320697598
and0.310288507
inineFunction
thennormalFunction
produces the output0.310213495
and5.515626813
The weirdness ends when the two pieces of code are extracted to individual functions. The only thing that comes to my mind is GC but the inline function shouldn't really have any overhead memory wise. Does someone have an idea why this might happen? Should I file a bug report?
Here are the two complete versions for clarity:
fun main() {
run {
var x = 0
println(measureNanoTime {
repeat(1_000_000_000) {
normalFunction {
x += it
}
}
} / 1E9)
}
run {
var x = 0
println(measureNanoTime {
repeat(1_000_000_000) {
inlineFunction {
x += it
}
}
} / 1E9)
}
}
fun main() {
run {
var x = 0
println(measureNanoTime {
repeat(1_000_000_000) {
inlineFunction {
x += it
}
}
} / 1E9)
}
run {
var x = 0
println(measureNanoTime {
repeat(1_000_000_000) {
normalFunction {
x += it
}
}
} / 1E9)
}
}