Skip to content

Implement fold for ArrayVecIterator over the remaining slice - #232

Open
g4lb wants to merge 2 commits into
Lokathor:mainfrom
g4lb:arrayvec-iterator-fold
Open

g4lb wants to merge 2 commits into
Lokathor:mainfrom
g4lb:arrayvec-iterator-fold

Conversation

@g4lb

@g4lb g4lb commented Nov 19, 2026 •

Copy link
Copy Markdown

ArrayVecIterator used the default Iterator::fold, which calls next once per item. Now it implements fold over the remaining slice with iter_mut().map(mem::take), so methods that use fold, such as sum and for_each, become one loop. TinyVecIterator now forwards fold to its inner iterator. The items and their order do not change.

Benchmark Before After Change
ArrayVec<[u32; 64]> into_iter().sum() 88.9 ns 5.35 ns -94.0%
inline TinyVec<[u32; 64]> into_iter().sum() 111 ns 20.9 ns -81.2%

No other benchmark changed significantly (23 local benchmarks for ArrayVec and TinyVec). I used 12 interleaved rounds of criterion and a Mann-Whitney test (Apple M5, rustc 1.98.0).

Checks:

  • cargo test --features=alloc,std,grab_spare_slice,latest_stable_rust and cargo +nightly test --all-features pass.
  • cargo +1.60.0 check --features=alloc,std,grab_spare_slice passes.
  • Old and new results, contents and panics matched on 4.5M random operations on ArrayVec and TinyVec.

@Shnatsel Shnatsel left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good to me! In theory this should speed up not just fold but also sum, for_each and reduce, because their default implementations are expressed in terms of fold.

The same technique can be applied to fold() in TinyVecIterator and ArrayVecDrain. Would be trickier to apply to SliceVecDrain and TinyVecDrain which need to restore state in the Drop impl.

try_fold is also worth optimizing in a similar fashion because a number of methods forward to it instead of fold: find, any, all, position, try_for_each.

@g4lb

g4lb commented Nov 19, 2026

Copy link
Copy Markdown
Author

Thanks, I measured them:

  • TinyVecIterator::fold: inline into_iter().sum() is 81% faster. I added it to this PR.
  • ArrayVecDrain::fold: drain(..).sum() is 14% slower, so I did not add it.
  • try_fold: it needs core::ops::Try, which is not stable.

@g4lb
g4lb requested a review from Shnatsel November 19, 2026 13:28
@Shnatsel

Copy link
Copy Markdown
Collaborator

oh yeah I forgot about try_fold not being implementable on stable, that is very silly

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