Skip to content

Use foreach and sizeHint in mapAccumulate - #85

Open
cheeseng wants to merge 1 commit into
dotty-staging:stdlib/map-accumulatefrom
artimahub:stdlib/map-accumulate-artima-cs
Open

Use foreach and sizeHint in mapAccumulate#85
cheeseng wants to merge 1 commit into
dotty-staging:stdlib/map-accumulatefrom
artimahub:stdlib/map-accumulate-artima-cs

Conversation

@cheeseng

Copy link
Copy Markdown

mapAccumulate traversed via a manual
val it = iterator; while (it.hasNext) { ... it.next() ... } loop,
even though nothing about the method needs iterator-specific
capability — no early exit, and every element is visited
unconditionally.

Switch to foreach, which dispatches to each collection's own native
traversal (e.g. List walking cons cells directly, index-based loops
for array-backed types) instead of allocating an Iterator and paying
two virtual calls (hasNext/next) per element.

This is safe for mapAccumulate specifically because the state (S) is
threaded sequentially through calls to f in traversal order, and
foreach/iterator are guaranteed to visit a given collection's
elements in the same order as each other — so the switch doesn't
change which elements state gets threaded through in which order.

Also add b.sizeHint(this): mapAccumulate always produces exactly one
B per input element, so unlike some other methods in this file where
a sizeHint would only be a guess, here the result size is known
exactly in advance and the builder can size itself accordingly.

No behavior changes.

The manual iterator/while loop offered no benefit over foreach here —
no early exit, and foreach/iterator are guaranteed to visit elements
in the same order for a given collection, so the sequential state
threading through f is unaffected by the switch. Use foreach for
native per-collection traversal instead of an allocated Iterator plus
two virtual calls (hasNext/next) per element.

Also add b.sizeHint(this): unlike updatedWith, mapAccumulate always
produces exactly one B per input element, so the result size is known
exactly in advance rather than just estimated.

No behavior changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant