Repository navigation
Closed
Labels
Description
This is just a crazy idea, which might not actually work out in practice, but...
At the moment, the interner does roughly as many allocations, as there are interned strings, as each string is a separate box. A more efficient approach would be to append strings to a growing stable storage (Vec<String>, where each String has capacity double of the previous one). That they, there would be roughly O(log(n)) allocations, which helps if original strings are not themselves separately allocated (if, for example, a compiler interns all identifiers from a single source file).
The minimal implementation doesn't look too bad:
use std::collections::HashMap;
pub struct Interner {
/// &'static strs point into self.buf
map: HashMap<&'static str, u32>,
vec: Vec<&'static str>,
/// Invariant: these strings are never resized
buf: Vec<String>,
}
impl Default for Interner {
fn default() -> Self {
Interner { map: HashMap::default(), vec: Vec::new(), buf: vec![String::with_capacity(128)] }
}
}
impl Interner {
pub fn intern(&mut self, name: &str) -> u32 {
if let Some(&idx) = self.map.get(name) {
return idx;
}
let name = unsafe { self.alloc(name) };
let idx = self.map.len() as u32;
self.map.insert(name, idx);
self.vec.push(name);
idx
}
pub fn lookup(&self, id: u32) -> &str {
self.vec[id as usize]
}
unsafe fn alloc(&mut self, name: &str) -> &'static str {
let mut last = self.buf.last_mut().unwrap();
if last.capacity() - last.len() < name.len() {
let cap = (last.capacity().max(name.len()) + 1).next_power_of_two();
self.buf.push(String::with_capacity(cap));
last = self.buf.last_mut().unwrap();
}
let start = last.len();
last.push_str(name);
&*(&last[start..] as *const str)
}
}Reacted by Italo Oliveira
Activity
Robbepop commentedon Mar 22, 2020
Thanks for the suggestion!
I also already made some thoughts how we can reduce the number of allocations.
Your proposal is interesting and I will experiment a bit with it over the weekend.
One behaviour of
StringInternerso far was that it can efficiently take ownership ofStringwhile it also accepts&str. I see this being in conflict with certain arena-like designs. Also I already experimented with usage ofPininStringInterner.I was also experimenting with integrating https://crates.io/crates/bucket_vec with which prevents re-allocations compared with a normal vector upon
push. So we can storeu8in it instead ofString. However, there are other complications with it.Have you looked into the
ustrcrate? It also is a string interner that allocates a whole chunk of data and puts strings in a similar vein into those chunks until they are filled to eventually just leak them and allocate another chunk of data. All to avoid heap allocations. Accordings to the authors it is faster thanstring_internerbut it is using far moreunsafecode as a trade off.matklad commentedon Mar 22, 2020
Yup, the above version is basically an inline version of
bucket_vec(but by usingStringdirectly one avoids unsafety related to utf8).I haven't seen
ustrbefore, thanks for the pointer. It indeed seems much more complicated, and leaking memory won't fit every use-case.Quick and non-scientific benchmarking shows that the above code (with
FxHashMap) slightly outperforms ustr:Robbepop commentedon Mar 22, 2020
Thanks for the benchmarks. So 20-30% faster is "slightly outperforms"? :P
Is the
many-allocsthe currentStringInternerandfew-alloca fork of yours or does it only benchmark inserts into anFxHashMap?I really like your proposal and if we can make sure that these changes actually improve performance for most use cases I am more than willing to either implement or merge a PR for it.
You are right about the
bucket_vecand that your solution without abucket_vecis probably a bit less involved and thus preferable.matklad commentedon Mar 22, 2020
few-allocsis the code from the original comment,many-allocsis this thing:I haven't actually tried
string-interner.My interners are from a hobby project of mine, which I am too embarrassed to make public rn :) I won't be submitting any PRs (but will probably write a blog about the technique), so feel free to run with the ideas!
matklad commentedon Mar 22, 2020
Published the impl in a blog :)
One improvement I've noticed is that
buf: String, full: Vec<String>is better thanbufs: Vec<String>, as it avoid a bound check when accessing the last buffer.Robbepop commentedon Mar 22, 2020
Nice read!
Some comments of mine:
Box<str>instead ofStringinvecand get rid of ausizeper buffer. Since there won't be too manyStringinstance this won't be very significant tbh. However, it would state the usage intent more clearly since you are not interested in mutating those string anymore when they are put into thevecvector.StrId(u32)you could useStrId(NonZeroU32)and offset all IDs by 1 to allows for certain optimizations withOption<StrId>.PinAPI instead of'staticreferences because that's what you are actually trying to do - pinning those strings and use the pinned references (Pin<&str>) invecandmap.Also thank you for trying out the trie approach. I wanted to experiment with that myself. :)
Robbepop commentedon Jul 12, 2020
@matklad Today I implemented a rough skeleton of your proposal into
StringInternerto a point were I was able to compare bothStringInternerwith and without your proposal.The results are inconclusive:
Below you can see the benchmarks from
StringInternerwith your proposal in comparison withStringInternerwithout your proposal. Whenever there is a negative number (e.g. inget_or_intern/fill emptyyour proposal is a speed-up, otherwise your proposal made the operation less efficient.The summary is that
get_or_internfor an initially emptyStringInternergot faster by approx 40%, however,get_or_internfor an already filledStringInterner(when interning is no longer needed later on) we see a 28% decline in performance. Same forresolveandget.I am not entirely done yet with implementing your proposal but from the first sight it highly depends on the use-case which internment mechanics you want to use.
I have to dig deeper into this but it seems that there are some significant trade-offs.
Robbepop commentedon Jul 14, 2020
This has been implemented in the new
string-interner 0.10within the newBucketBackendthat is used as default backend for theStringInterner.Thanks @matklad for proposing this implementation!