kotlin icon indicating copy to clipboard operation
kotlin copied to clipboard

Avoid Iterator allocation in Wasm Backend operations

Open ApoloApps opened this issue 3 months ago • 4 comments

Add memoryOptimizedForEach and memoryOptimizedForEachIndexed to avoid allocating an Iterator (index-based for loops, not default iterator for loop) and apply them to Wasm Backend for better performance overall. This could also be done for intermediate operations like map, mapIndexed, and others but this is only a little change focused on improving memory consumption in Wasm Backend operations and compilation

ApoloApps avatar Sep 10 '25 23:09 ApoloApps

I would prefer this to be named based on how it behaves, not a relationship to the "normal" forEach.

If you run this new function on non-random access-based list, you actually thrash the cache lines of the CPU making it very much not memory optimized. Heap allocation and virtual dispatch counts are not the only memory that needs considered.

I tend to call these indexBasedForEach which describes the implementation, and hopefully makes it more obvious that it's a Bad Idea™ to use on something like a linked list.

JakeWharton avatar Sep 11 '25 01:09 JakeWharton

i tried to mantain consistent naming so thats why i changed to mention the index access in the kdoc. renaming it!

ApoloApps avatar Sep 11 '25 11:09 ApoloApps

@ilgonmic not sure the reviewers are correct

ApoloApps avatar Sep 15 '25 15:09 ApoloApps

cc @bashor

ilgonmic avatar Sep 15 '25 15:09 ilgonmic