mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:42:27 +00:00
craft-rtf: one index lookup per insert, and no key String for a known author
`Interned::insert` looked the key up and then inserted it, two probes for a new key. It now goes through `HashMap::entry`, one probe either way, and counts that probe itself, so the tests count what the index does. `author()` built a `String` key on every call. It now looks the author up borrowed first, and allocates only for a new one. Review on #1467.
This commit is contained in:
1 parent
74495a579a
commit
14b2ebb7c2
3 files changed
+22
-8
No files matched your search
@@ -306,7 +306,13 @@ impl Writer {
|
||||
if a.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
authors.insert(a.to_string(), || a.to_string()) + 1
|
||||
// A borrowed lookup first: most calls name an author already in the table, and need no
|
||||
// `String` for the key.
|
||||
let i = match authors.get(a) {
|
||||
Some(i) => i,
|
||||
None => authors.insert(a.to_string(), || a.to_string()),
|
||||
};
|
||||
i + 1
|
||||
}
|
||||
|
||||
/// Control words of a tracked insertion and deletion (`\revised`, `\deleted`).
|
||||
|
||||
@@ -1207,6 +1207,8 @@ fn many_distinct_fonts_colours_and_authors_take_constant_steps_each() {
|
||||
};
|
||||
let mut out = String::new();
|
||||
let steps = crate::write::lookup_steps(|| w.para(&p, false, None, "\\par", &mut out));
|
||||
// One lookup each for the font and the colour, and two for a new author: the borrowed
|
||||
// lookup, then the insert.
|
||||
assert!(steps <= 4 * n, "{steps} steps for {n} runs");
|
||||
assert!(out.contains(&format!("\\f{n}\\cf{n}")), "the last run names the last font and colour");
|
||||
assert!(out.contains(&format!("\\crauth{n}")), "the last run names the last author");
|
||||
|
||||
+13
-7
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::borrow::Borrow;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use std::fmt::Write;
|
||||
use std::hash::Hash;
|
||||
|
||||
@@ -90,15 +91,20 @@ impl<T, K: Eq + Hash> Interned<T, K> {
|
||||
self.index.get(key).copied()
|
||||
}
|
||||
|
||||
/// The place of the entry with `key`, adding `item()` at the end when there is none.
|
||||
/// The place of the entry with `key`, adding `item()` at the end when there is none: one
|
||||
/// lookup in the index either way.
|
||||
pub(crate) fn insert(&mut self, key: K, item: impl FnOnce() -> T) -> usize {
|
||||
if let Some(i) = self.get(&key) {
|
||||
return i;
|
||||
#[cfg(test)]
|
||||
STEPS.with(|s| s.set(s.get() + 1));
|
||||
match self.index.entry(key) {
|
||||
Entry::Occupied(e) => *e.get(),
|
||||
Entry::Vacant(e) => {
|
||||
self.items.push(item());
|
||||
let i = self.items.len() - 1;
|
||||
e.insert(i);
|
||||
i
|
||||
}
|
||||
}
|
||||
self.items.push(item());
|
||||
let i = self.items.len() - 1;
|
||||
self.index.insert(key, i);
|
||||
i
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user