Search code examples
androidkotlin

When to use FastForEach vs ForEach


I am finding a reason why there is fastForEach (I checked its included in androidx.compose.ui.util package) in kotlin when we already have forEach? Why they used fast with it? When we should use it when to avoid. Proper examples to understand will be better.


Solution

  • From the reference documentation:

    Iterates through a List using the index and calls action for each item. This does not allocate an iterator like Iterable.forEach

    Do not use for collections that come from public APIs, since they may not support random access in an efficient way, and this method may actually be a lot slower. Only use for collections that are created by code we control and are known to support random access.

    So in short, it is a variant of forEach that avoids object allocation and thus can be more performant for collections that support random access. There is a related thread on kotlinlang.org with some more in-depth discussions.

    As not all collections support random access (cf. RandomAccess; the referenced thread even mentions some where it might cause actual problems), and as with all performance improvements, you'll only know if you do tests and measure, I'd personally stick with the default forEach until you notice a problem in that part of the code. And then you can consider replacing it and see if that is indeed the root issue.