kotlin-python icon indicating copy to clipboard operation
kotlin-python copied to clipboard

Don't create intermediate collections in chains of functions calls like `.filter.flatMap.zip`

Open krzema12 opened this issue 3 years ago • 2 comments

Originally created by @SerVB.

krzema12 avatar Nov 23 '21 07:11 krzema12

Aren't sequences what you mean? Sequences are lazy, extension functions on iterables are eager.

krzema12 avatar Nov 23 '21 07:11 krzema12

val result = a.filter(cond).map(mapper) actually contains inlined intermediate collections like this:

val filterResult = mutableListOf()
for (aa in a) {
  if (cond(aa)) {
    filterResult.add(aa)
  }
}
val result = mutableListOf()
for (aa in filterResult) {
    result.add(mapper(aa))
}

We don't need filterResult here because it's generated and isn't used by the programmer directly.

The generated inlining could be simplified and optimized if we get rid of the intermediate filterResult:

val result = mutableListOf()
for (aa in a) {
  if (cond(aa)) {
    result.add(mapper(aa))
  }
}

It's not exactly how a sequence works because AFAIR it doesn't generate inlined code. So I believe it could be more effective than sequences too.

SerVB avatar Nov 26 '21 10:11 SerVB