Is the bytecode shown by Intellij the final byteco...
# announcements
d
Is the bytecode shown by Intellij the final bytecode produced by the kotlin compiler, or is it optimized further? As an example, the following code was produced by the Intellij
Copy code
(0..listA.size - 1).filter{ listA[it] < listB[it] }.forEach { return true}; return false
as a result of intention action to fix "LoopToCallChain` warning on the following loop:
Copy code
for (i in 0..listA.size - 1) if (listA[i] < listB[i]) return true; return false
The bytecode in the IDE of former snippet shows creation of additional objects, and more importantly, running the comparison for the full list, rather than returning early. Does the compiler at build time optimize it?
a
@deepanshu: your
(0..listA.size-1)
creates a Range which is an eager Iterator. so running
filter { }
filters the whole list before running
forEach { }
. If you want it to be lazily evaluated (returning early) you need to use
(0..x).asSequence().filter { }
and btw, there is
any
for Iterables (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/any.html) which does exactly what you do with
filter().forEach()
. your code can be written as
return (0..listA.size -1).any { listA[it] < listB[it] }
d
Thanks @Andreas Sinz