I’m finding that R8 does not optimize the followin...
# android
l
I’m finding that R8 does not optimize the following code:
Copy code
"foo".startsWith("f")
while the following becomes
true
in bytecode:
Copy code
("foo" as java.lang.String).startsWith("f")
I think I understand why from the perspective of R8, but isn’t this a bit of a problem for Kotlin? I imagine there may be quite a few methods that could be optimized but are not?
s
I tried a small example with Kotlin compiler 2.3.10 and R8 9.4.14 in release class-file mode. Before R8, the Kotlin call goes through
StringsKt.startsWith$default
, while the Java cast calls
String.startsWith
directly. In my test, R8 reduced both methods to
true
. My setup used the Kotlin 2.4.20 standard library and wasn’t an Android APK build, so it may differ from yours. Which Kotlin and R8/AGP versions are you using?
l
It’s the size of the example. In a bigger app, R8 will not inline it with reasons such as these: > R8: Method
boolean kotlin.text.StringsKt__StringsJVMKt.startsWith(java.lang.String, java.lang.String, int, boolean)
was not inlined into `boolean kotlin.text.StringsKt__StringsJVMKt.startsWith$default(java.lang.String, java.lang.String, int)`: not inlining due to code size heuristic (inlinee may have multiple callers and is not considered trivial). (You can get the reason with a
-whyareyounotinlining
rule.)
You can force inline with
-alwaysinline
(unsupported but works), and for this method it saves me around 1KB for a 3MB app. Maybe not a big deal, but there are likely more methods like this that and the overall effect on the apk size might be significant. But maybe more importantly, this kind of a method is sometimes used with constant text, and if it can be optimized to
true
it can lead to further optimizations in the caller.
s
Thanks, that explains why my small example behaved differently. The inlining diagnostic makes the trade-off clearer: R8 is considering the helper’s size and multiple callers, while inlining could also expose constants to the caller. A small example with enough callers to preserve that behavior could be useful in an R8 issue. I’d be cautious about relying on
-alwaysinline
in a production build given that it’s unsupported.