scala-dev
scala-dev copied to clipboard
Closure state minimization
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".
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
}
}