Could Kotlin automatically recognize when it would...
# language-proposals
d
Could Kotlin automatically recognize when it would be safe to convert a call like
listOf(…).forEach { … }
into
arrayOf(…) { … }
(or appropriate primitive array)?
arrayOf
is typically discouraged within Kotlin because it has some wonky behaviors, but in specific cases like this, which I’ve found to be a fairly common pattern, it would have identical functionality, while eliminating two object allocations (outer list, iterator) and simplifying the looping logic.
y
It doesn’t But, a minifier like ProGuard or R8 might detect that Also, I’d bet good money that JIT optimizes this away, so the performance should be about the same
👀 1
j
R8 will not do that
Even if you got
listOf
inlined into the call site, the iteration semantics of
ArrayList
are defined in the platform and not in code that R8 can see. So for all it knows the elements are produced backwards in certain conditions.
d
Thanks, good to know. I expect the JIT to eventually kick in, but that doesn't help much in cases like Android app starts or where this pattern is called many times, but in many different places rather than just one.