I don’t have much to contribute to the main idea itself, but specifically about the inlined code duplication issue, I feel like the solution here will come from bytecode optimizations in the Kotlin compiler because it can be smart enough to have the
action in literally a go-to block and have both the fast and slow implementation just go-to that block. Also, remember that most applications that are actually released used some form of minifier, and so I wouldn’t be quick to focus too much on the code duplication issue since a minifier could and should be able to notice the same chunk of code duplicated twice and use the go-to solution for that (in fact I bet most already do). I’d suggest maybe make a small sample and compile it then run it through Proguard or an equivalent and decompile the minified version.
Regardless, there’s still a little issue with this puzzle, which is that the inline block duplication will slow down compilation speed, but there’s many-a-ways for that to be solved. Firstly, of course, the compiler can be smart enough to do the go-to solution. But even if not, there can be cases where it is statically-known at compile-time whether or not something
is RandomAccess (like in your example ArrayList would be statically-known to implement RandomAccess) and so it then follows that the whole
else branch in the inlined
fastForEach2 can just be statically-removed.
So yeah just simply minifiers are really trained to handle cases like this and so really the “bigger” concern here would be looking at quirks like
CopyOnWriteArrayList and how to handle those