Skip to content

perf: select better hashing algorithm for access maps #398

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 29, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions crates/bevy_mod_scripting_core/src/bindings/access_map.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! A map of access claims used to safely and dynamically access the world.

use std::hash::{BuildHasherDefault, Hasher};

use bevy::{
ecs::{component::ComponentId, world::unsafe_world_cell::UnsafeWorldCell},
prelude::Resource,
Expand Down Expand Up @@ -315,9 +317,34 @@ pub trait DynamicSystemMeta {
fn access_first_location(&self) -> Option<std::panic::Location<'static>>;
}

#[derive(Debug, Default, Clone)]
#[derive(Default)]
/// A hash function which doesn't do much. for maps which expect very small hashes.
/// Assumes only needs to hash u64 values, unsafe otherwise
struct SmallIdentityHash(u64);
impl Hasher for SmallIdentityHash {
fn finish(&self) -> u64 {
self.0
}

fn write(&mut self, bytes: &[u8]) {
// concat all bytes via &&
// this is a bit of a hack, but it works for our use case
// and is faster than using a hash function
#[allow(clippy::expect_used, reason = "cannot handle this panic otherwise")]
let arr: &[u8; 8] = bytes.try_into().expect("this hasher only supports u64");
// depending on endianess

#[cfg(target_endian = "big")]
let word = u64::from_be_bytes(*arr);
#[cfg(target_endian = "little")]
let word = u64::from_le_bytes(*arr);
self.0 = word
}
}

#[derive(Default, Debug, Clone)]
struct AccessMapInner {
individual_accesses: HashMap<u64, AccessCount>,
individual_accesses: HashMap<u64, AccessCount, BuildHasherDefault<SmallIdentityHash>>,
global_lock: AccessCount,
}

Expand Down Expand Up @@ -795,6 +822,8 @@ pub(crate) use with_global_access;

#[cfg(test)]
mod test {
use std::hash::Hash;

use super::*;

#[test]
Expand Down Expand Up @@ -1200,4 +1229,12 @@ mod test {
assert!(!subset_access_map.claim_read_access(2));
assert!(!subset_access_map.claim_write_access(2));
}

#[test]
fn test_hasher_on_u64() {
let mut hasher = SmallIdentityHash::default();
let value = 42u64;
value.hash(&mut hasher);
assert_eq!(hasher.finish(), 42);
}
}
Loading