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:
- normalFunctionthen- inlineFunctionproduces the output- 0.320697598and- 0.310288507
- inineFunctionthen- normalFunctionproduces the output- 0.310213495and- 5.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)
    }
}
