From 6a5ab34a2db56c22e1051dfaabf98322c50f53bd Mon Sep 17 00:00:00 2001 From: mat Date: Sun, 23 Feb 2025 17:39:17 +0000 Subject: azalea-language now does a binary search instead of a hashmap lookup --- azalea-language/src/lib.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'azalea-language/src') diff --git a/azalea-language/src/lib.rs b/azalea-language/src/lib.rs index bb5d144e..d86a2697 100755 --- a/azalea-language/src/lib.rs +++ b/azalea-language/src/lib.rs @@ -4,9 +4,22 @@ use std::{collections::HashMap, sync::LazyLock}; use compact_str::CompactString; -pub static STORAGE: LazyLock> = - LazyLock::new(|| serde_json::from_str(include_str!("en_us.json")).unwrap()); +pub static STORAGE: LazyLock> = LazyLock::new(|| { + let json = + serde_json::from_str::>(include_str!("en_us.json")) + .unwrap(); + let mut json = json.into_iter().collect::>(); + + // sort by key to make binary search work + json.sort_by(|a, b| a.0.cmp(&b.0)); + + json +}); pub fn get(key: &str) -> Option<&str> { - STORAGE.get(key).map(|s| s.as_str()) + let key = CompactString::from(key); + let storage = &*STORAGE; + // more memory efficient than a hashmap lookup + let index = storage.binary_search_by(|(k, _)| k.cmp(&key)); + index.ok().map(|i| storage[i].1.as_str()) } -- cgit v1.2.3