Remove unessesary iteration#1
Merged
grantshandy merged 1 commit intograntshandy:mainfrom Mar 16, 2022
Merged
Conversation
See !1 for details
Owner
|
Thanks! I didn't think about using |
FWIW to this diff --git a/tests/speed.rs b/tests/speed.rs
index 663c7b6..256eece 100644
--- a/tests/speed.rs
+++ b/tests/speed.rs
@@ -24,7 +24,7 @@ fn speed() {
fn test() -> i64 {
let time_before = chrono::Utc::now();
- assert!(imei::valid("490154203237518"));
+ assert!(luhn3::decimal::valid("490154203237518".as_bytes()));
// pass "--nocapture" to show time difference
let difference = chrono::Utc::now()Now, the benchmark itself comes with some overhead - if I comment out the check and simply run the measuring loop result is Which means imei code takes 54-31 = 23ns and luhn3 takes 39-31 = 8ns. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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::countwill 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 --releasethough... 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
luhn3andisincrates are the ones I'm thinking of.