`collect` gives different result than `for` loop

I’ve seen such behavior a few times. It usually happens when length claims one length, but actually iterating produces fewer elements. collect preallocates based on length, but doesn’t shrink to the number of elements actually produced (counting them may be slow).

Would be interesting if we could add a LengthBounded() trait to opt into that allows shrinking the resulting collection if fewer than length(itr) elements were actually produced.

2 Likes