https://kotlinlang.org logo
#announcements
Title
# announcements
d

deepanshu

05/01/2017, 9:21 AM
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

Andreas Sinz

05/01/2017, 9:41 AM
@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

deepanshu

05/01/2017, 9:53 AM
Thanks @Andreas Sinz
2 Views