Proposal: Add opportunity to pass primitive type arguments in Inlined lambda "by reference"

But my main point mostly about the feature…

I waste my time performing a JMH benchmark.

The tested code is:

fun inlined(n1: Int, n2: Int, hole: Blackhole) {
    var a = n1
    var b = n2
    a = a * a
    b = b * b * b
    hole.consume(a)
    hole.consume(b)
}

fun regular(n1: Int, n2: Int, hole: Blackhole) {
    val (a, b) = pow(n1, n2)
    hole.consume(a)
    hole.consume(b)
}

fun pow(a: Int, b: Int) = PowResult(a * a, b * b * b)

data class PowResult(val a: Int, val b: Int)

My results are:

Benchmark            (n1)  (n2)   Mode  Cnt         Score         Error  Units
MyBenchmark.inlined     2     3  thrpt   25  61767631,934 ± 1383593,934  ops/s
MyBenchmark.regular     2     3  thrpt   25  68815306,595 ± 1256675,856  ops/s

Again, please consider to measure supposed enhancements.

I wish to cite my friend Mario:

Programming languages don’t differ much in what they make possible, but in the kind of mistakes they make impossible
https://twitter.com/mariofusco/status/927168145621741569

2 Likes

The proposed changes do not make any sense on JVM, since JVM inlining is very smart by itself. It could give some advantage in Kotlin-Native, but I still think it does not worth the effort.

In my experience, there are lot of cases, where C-style “let’s optimize something just because we can and because we do not have a profiler” damages performance instead of increasing it.

1 Like

So far, I struggle to see really common or extremely appealing use cases for this feature. What application areas do you have in mind?

1 Like

Well it have some very rare applications in high performance computing, where you are forced to use C-style to avoid additional variable allocation, but those cases are rather limited and I can’t think of an example, where it could not be done without inventing new language features.

I think that inlines still have some growth points, but it is mostly about inner mechanics like equals, private constructors and smart boxing elimination, not about syntax.

1 Like