kotlin-python
kotlin-python copied to clipboard
Don't create intermediate collections in chains of functions calls like `.filter.flatMap.zip`
Originally created by @SerVB.
Aren't sequences what you mean? Sequences are lazy, extension functions on iterables are eager.
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.