Skip to content

Constructor inlining #17721

Closed
Closed
@scf37

Description

@scf37

Dotty has method inlining but it is incomplete without constructor inlining.

Motivation

trait JsonReader[A] {
  def read(it: JsonIterator): A
}

class SeqJsonReader[A](inner: JsonIterator => A) {
  inline def read(it: JsonIterator): A = ..... // won't inline as expected because constructor parameters are not inlined
}

inline given [A]: SeqJsonReader[A] = new SeqJsonReader(it => summon[JsonReader[A]].read(it)) // summoned read() contents will be inlined

Problem

  class Foo (a: String) {
    inline def foo(): Unit = println(a)
  }

  def print() = new Foo("hello").foo()

Compiles to:

public void print() {
    Foo Foo_this = new Foo("hello");
    Predef$.MODULE$.println((Object)Foo_this.inline$a());
}

which is wasted allocation.

Therefore when inlining method referencing constructor parameters only, there is no need to create object instance.

Possible solutions

  1. Inline classes - kind of explored here https://odersky.github.io/sips//pending/inline-classes.html
  2. Perform this optimization automatically

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions