scala-dev icon indicating copy to clipboard operation
scala-dev copied to clipboard

Closure state minimization

Open lrytz opened this issue 10 years ago • 1 comments
trafficstars

Eliminate unused fields from closures. See Miguel's prototype: https://github.com/scala/scala/commit/5d4e477, also the paper "Optimizing Closures in O(0) time".

lrytz avatar Oct 05 '15 13:10 lrytz

Related example from Martin's talk (https://youtu.be/NW5h8d_ZyOs?t=30m49s).

The problem is not that non-used values are captured, but that the closure only uses a specific field of the captured value.

class C {
  def ship(f: () => Unit) = ???
  val data = List(1,2,3)
  val sum = data.sum
  ship(() => println(sum)) // captures this, serializing the closure includes the data
}

solution:

class C {
  def ship(f: () => Unit) = ???
  val data = List(1,2,3)
  val sum = data.sum
  {
    val s = sum
    ship(() => println(s)) // captures only the local variable s
  }
}

lrytz avatar Oct 21 '15 14:10 lrytz