diff --git a/src/utils/string_key.rs b/src/utils/string_key.rs index 3a152b3..b701648 100644 --- a/src/utils/string_key.rs +++ b/src/utils/string_key.rs @@ -1,5 +1,6 @@ +use hashbrown::HashMap; use std::hash::{Hash, Hasher}; -use std::sync::Arc; +use std::sync::{Arc, Mutex, Weak}; /// StringKey is an immutable string that is used for indexing of hashmaps or equality a lot. /// By reference counting the string instead of copying, and caching the hash, we can get some @@ -11,6 +12,10 @@ pub struct StringKey { hash: u32, } +lazy_static::lazy_static! { + static ref STRING_CACHE: Mutex>> = Mutex::new(HashMap::new()); +} + impl StringKey { pub const fn get_hash_const(s: &[u8; N]) -> u32 { let mut crc: u32 = 0xffffffff; @@ -33,10 +38,22 @@ impl StringKey { pub fn new(s: &str) -> Self { let hash = StringKey::get_hash(s); - Self { + let mut cache = STRING_CACHE.lock().unwrap(); + let cached_value = cache.get(&hash); + if let Some(cached_value) = cached_value { + if let Some(cached_value) = cached_value.upgrade() { + return Self { + str: cached_value, + hash, + }; + } + } + let v = Self { str: Arc::new(s.to_string()), hash, - } + }; + cache.insert(hash, Arc::downgrade(&v.str)); + v } pub fn str(&self) -> &str {