Avoid rechecking for duplicates in IdOrdMap::from_iter_unique#303
Conversation
|
Thanks! Would you be willing to extend the same fix to Also, while we're optimizing here, |
|
Thanks for the very quick feedback! 🙇
Sure sure, happy to take a crack at it -- pushed a few more commits. A note on what I did for It's possible there's a better/cleaner solution here with a bit more refactoring (e.g. maybe switching Unrelated to this, the usage of |
| Entry::Vacant(_) => { | ||
| self.insert_known_unique_impl(value); | ||
| None |
There was a problem hiding this comment.
I would instead add a (non-public) VacantEntry::insert_known_unique that inserts the value without recomputing the hash (instead grabbing it from the VacantEntry).
There was a problem hiding this comment.
Ah, I like that -- thank you! 👍 And now it actually does do the thing that's written on the tin in the comment -- it avoids both the extra duplicate check and recomputing the hash (which I reintroduced 🙈). Done in 3017f0a.
EDIT: just a small note: since the method is non-public and the only caller doesn't need any result, it seemed okay for now to not return anything from the method.
Preparation for #303. * Add a standard test for from_iter_unique. * Add `FlipItem` tests.
sunshowers
left a comment
There was a problem hiding this comment.
Thanks! I pushed a few tweaks.
Hello, again! 👋 While I was reading about
IdOrdMap::from_iter_uniqueand writing up #300, it occurred to me that the method might be doing extra work.Specifically, it seems like we're checking for duplicates twice:
map.entry(value.key())and that tells us whether this is a duplicate.Entry::Vacantbranch (i.e. after we already determined that this is not a duplicate) whenentry.insert_ref(value)is called.insert_refcallsinsert_unique_implwhich also checks for duplicates.So, if I understood things correctly, we're checking for duplicates twice for a single unique-key insert, and once should be enough.
This PR is an attempt at a minimal change to avoid that extra work: extract the insertion logic out of
insert_unique_implso that it can be reused. This new method,insert_known_unique_impl(naming suggestions always welcome 🙈), is private and assumes that it doesn't need to check for duplicates itself because that has been done by the callers.This method is what we then call from both
insert_unique_implandfrom_iter_uniqueafter those methods determined that the value's key is unique. And that then removes the extra check for duplicates infrom_iter_unique.Again, I tried to start with a minimal diff, and if the general idea makes sense and feels valuable -- happy to iterate on the implementation based on feedback!