Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize replicateA to have same recursive structure as replicateA_ #4233

Merged
merged 1 commit into from
Jun 13, 2022

Conversation

johnynek
Copy link
Contributor

follow up to #4208

This implements replicateA in the same was as replicateA_. The benefit over using traverse, which was the previous implementation, is that traverse ignores that all the items in the sequence are identical. This implementation leverages that to get O(log n) calls to map2 instead of O(n) calls to map2.

Note, it is still an O(n) method in the worst case since finally we have to materialize the List[A] which is length n, but often it is the map2 calls that are expensive, not iterating the list.

@johnynek johnynek requested a review from armanbilge June 12, 2022 17:59
@armanbilge armanbilge added this to the 2.8.0 milestone Jun 12, 2022
@armanbilge
Copy link
Member

This is really neat! What do you think about a tail-recursive implementation? I gave it a try in 1b55564.

@johnynek
Copy link
Contributor Author

I personally don't think it is worth it because the depth is already log N. So even if you use Int.MaxValue here you are dealing with 31 recursive calls.

If you're really interested, we can do it. A loop is better than depth 31, but I think the trade-off is more complex implementation in return for a very rare case where you can afford 1 additional call but not 31.

Copy link
Member

@armanbilge armanbilge left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can merge yours and I might put up mine as another PR 👍

@johnynek johnynek merged commit 7233e8a into main Jun 13, 2022
@armanbilge armanbilge deleted the oscar/20220612_optimize_replicateA branch June 13, 2022 03:09
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.

2 participants