Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I was reading your code and noticed that you were iterating the string twice where you didn't need to.
Iterator::count
will consume the iterator. Of course,chars.clone()
only duplicates the iterator (since the iter holds only a reference to the string), but it still needs to consume that copy to count the number of items. This extra iteration is unnecessary because thestr
(that you got fromAsRef::as_ref
) stores the length of its buffer.On my hardware, your code gets 2227 ns average. With my changes, I got 1540 ns. The kicker is
cargo test --release
though... 90 ns with yours and 78 ns with mine. Looks like the compiler guys are better at optimizing than either of us.There's a couple other versions of basically the same algorithm that are more aggressively optimized using arrays, the
luhn3
andisin
crates are the ones I'm thinking of.