krzema12 / kotlin-python

Python target for the Kotlin Programming Language. See https://github.com/krzema12/kotlin-python/tree/python-backend/python
https://discuss.kotlinlang.org/t/idea-python-backend/19852
48 stars 1 forks source link

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

Open krzema12 opened 2 years ago

krzema12 commented 2 years ago

Originally created by @SerVB.

krzema12 commented 2 years ago

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

SerVB commented 2 years ago

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.