-
Notifications
You must be signed in to change notification settings - Fork 292
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sometimes a map is constructed when it is known that all keys are unique (e. e. if keys are coming from another map or from a sorted/deduplicated iterator). In this case we can make insertion faster by skipping a check that a key already exists in the map. `insert_unique_unchecked` is guaranteed to be memory-safe, but does not guarantee anything beyond that: if inserted key is not unique, `HashMap` can panic, loop forever, return incorrect entry etc. Added simple benchmark. `insert_unique_unchecked` is about 30% faster than `insert`. Your mileage may vary of course. Similar PR was [added to `indexmap` crate](indexmap-rs/indexmap#200) and they asked to discuss the name of the operation with `hashbrown` crate owners to come to the same naming convention (if `hashbrown` is willing to have the same operation).
- Loading branch information
1 parent
728f9e8
commit 8d6c278
Showing
3 changed files
with
89 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
//! Compare `insert` and `insert_unique_unchecked` operations performance. | ||
#![feature(test)] | ||
|
||
extern crate test; | ||
|
||
use hashbrown::HashMap; | ||
use test::Bencher; | ||
|
||
#[bench] | ||
fn insert(b: &mut Bencher) { | ||
let keys: Vec<String> = (0..1000).map(|i| format!("xxxx{}yyyy", i)).collect(); | ||
b.iter(|| { | ||
let mut m = HashMap::with_capacity(1000); | ||
for k in &keys { | ||
m.insert(k, k); | ||
} | ||
m | ||
}); | ||
} | ||
|
||
#[bench] | ||
fn insert_unique_unchecked(b: &mut Bencher) { | ||
let keys: Vec<String> = (0..1000).map(|i| format!("xxxx{}yyyy", i)).collect(); | ||
b.iter(|| { | ||
let mut m = HashMap::with_capacity(1000); | ||
for k in &keys { | ||
m.insert_unique_unchecked(k, k); | ||
} | ||
m | ||
}); | ||
} |
This file contains 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
This file contains 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