Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui: Hash a GlobalElementId once, when it is built (#64209)
Jason Lee1dd9bbfd71cd
diff --git a/crates/gpui/src/element.rs b/crates/gpui/src/element.rsindex d6556258e15..cedf3046c77 100644--- a/crates/gpui/src/element.rs+++ b/crates/gpui/src/element.rs@@ -38,7 +38,6 @@ use crate::{FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,util::FluentBuilder, window::with_element_arena,};-use derive_more::{Deref, DerefMut};use std::{any::Any,fmt::{self, Debug, Display},@@ -211,12 +210,82 @@ pub trait ParentElement {}/// A globally unique identifier for an element, used to track state across frames.-#[derive(Deref, DerefMut, Clone, Default, Debug, Eq, PartialEq, Hash)]-pub struct GlobalElementId(pub(crate) Arc<[ElementId]>);+///+/// The hash of the id path is computed once, when the id is built. Every+/// element with an id is looked up in the element-state maps of two frames+/// and recorded as accessed on every frame it is drawn, and each of those+/// hashes the whole path — every ancestor's id, string names byte by byte —+/// so on a deep tree the hashing alone was a visible share of a frame.+#[derive(Clone, Debug)]+pub struct GlobalElementId {+ ids: Arc<[ElementId]>,+ hash: u64,+}++/// The hash of an empty id path; every path hash is folded from it with+/// [`extend_path_hash`], one id at a time, so the window can keep the hash+/// of each prefix of its id stack and never re-hash a path.+pub(crate) const EMPTY_PATH_HASH: u64 = 0;++/// The hash of the path `prefix` + `id`, given the hash of `prefix`.+pub(crate) fn extend_path_hash(prefix: u64, id: &ElementId) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut hasher = collections::FxHasher::with_seed(prefix as usize);+ id.hash(&mut hasher);+ hasher.finish()+}++impl GlobalElementId {+ pub(crate) fn new(ids: &[ElementId]) -> Self {+ let hash = ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash);+ Self::with_hash(ids, hash)+ }++ /// `ids` with its hash already known, as the window's id stack keeps it.+ pub(crate) fn with_hash(ids: &[ElementId], hash: u64) -> Self {+ debug_assert_eq!(hash, ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash));+ Self {+ ids: Arc::from(ids),+ hash,+ }+ }++ pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {+ accesskit::NodeId(self.hash)+ }+}++impl Default for GlobalElementId {+ fn default() -> Self {+ Self::new(&[])+ }+}++impl std::ops::Deref for GlobalElementId {+ type Target = [ElementId];++ fn deref(&self) -> &Self::Target {+ &self.ids+ }+}++impl PartialEq for GlobalElementId {+ fn eq(&self, other: &Self) -> bool {+ self.hash == other.hash && (Arc::ptr_eq(&self.ids, &other.ids) || self.ids == other.ids)+ }+}++impl Eq for GlobalElementId {}++impl std::hash::Hash for GlobalElementId {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ state.write_u64(self.hash);+ }+}impl Display for GlobalElementId {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- for (i, element_id) in self.0.iter().enumerate() {+ for (i, element_id) in self.ids.iter().enumerate() {if i > 0 {write!(f, ".")?;}@@ -226,15 +295,6 @@ impl Display for GlobalElementId {}}-impl GlobalElementId {- pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {- use std::hash::{Hash, Hasher};- let mut hasher = std::hash::DefaultHasher::default();- self.hash(&mut hasher);- accesskit::NodeId(hasher.finish())- }-}-trait ElementObject {fn inner_element(&mut self) -> &mut dyn Any;@@ -360,7 +420,7 @@ impl<E: Element> Drawable<E> {} => {if let Some(element_id) = self.element.id() {window.element_id_stack.push(element_id);- debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);+ debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);}let bounds = window.layout_bounds(layout_id);@@ -393,7 +453,7 @@ impl<E: Element> Drawable<E> {crate::window::a11y::debug::NodeDebugInfo {synthetic: false,view,- element_id: global_id.0.last().map(|id| format!("{id:?}")),+ element_id: global_id.last().map(|id| format!("{id:?}")),source_location,},);@@ -422,7 +482,7 @@ impl<E: Element> Drawable<E> {.view_type_names.get(&window.current_view()).copied(),- element_id: global_id.0.last().map(|id| format!("{id:?}")),+ element_id: global_id.last().map(|id| format!("{id:?}")),source_location: self.element.source_location(),};let mut builder = A11ySubtreeBuilder::new(@@ -473,7 +533,7 @@ impl<E: Element> Drawable<E> {} => {if let Some(element_id) = self.element.id() {window.element_id_stack.push(element_id);- debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);+ debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);}window.next_frame.dispatch_tree.set_active_node(node_id);@@ -796,7 +856,7 @@ impl Element for Empty {#[inline(never)]fn prepare_element_id(element_id: ElementId, window: &mut Window) -> GlobalElementId {window.element_id_stack.push(element_id);- GlobalElementId(Arc::from(&*window.element_id_stack))+ window.element_id_stack.global_id()}#[cfg(any(feature = "inspector", debug_assertions))]@@ -806,8 +866,138 @@ fn prepare_inspector_id(window: &mut Window,) -> InspectorElementId {let path = InspectorElementPath {- global_id: GlobalElementId(Arc::from(&*window.element_id_stack)),+ global_id: window.element_id_stack.global_id(),source_location: source,};window.build_inspector_element_id(path)}++#[cfg(test)]+mod global_element_id_tests {+ use super::*;+ use std::hash::{Hash, Hasher};++ fn path(depth: usize, leaf: u64) -> Vec<ElementId> {+ let mut ids: Vec<ElementId> = (0..depth as u64)+ .map(|level| ElementId::NamedInteger("some-container-element".into(), level))+ .collect();+ ids.push(ElementId::NamedInteger("leaf".into(), leaf));+ ids+ }++ fn fx_hash(value: &impl Hash) -> u64 {+ let mut hasher = collections::FxHasher::default();+ value.hash(&mut hasher);+ hasher.finish()+ }++ #[test]+ fn equal_paths_are_equal_and_hash_alike() {+ let a = GlobalElementId::new(&path(8, 1));+ let b = GlobalElementId::new(&path(8, 1));+ let c = GlobalElementId::new(&path(8, 2));+ let shallower = GlobalElementId::new(&path(7, 1));+ assert_eq!(a, b);+ assert_eq!(fx_hash(&a), fx_hash(&b));+ assert_eq!(a.accesskit_node_id(), b.accesskit_node_id());+ assert_ne!(a, c);+ assert_ne!(a, shallower);+ assert_ne!(fx_hash(&a), fx_hash(&c));+ assert_eq!(&*a, path(8, 1).as_slice());+ assert_eq!(a.to_string(), b.to_string());+ assert_eq!(GlobalElementId::default(), GlobalElementId::new(&[]));+ }++ /// A window of `items` columns of `depth` nested stateful divs — the+ /// shape of a list of cards — drawn from scratch on every frame.+ struct DeepStatefulTree {+ items: usize,+ depth: usize,+ }++ impl crate::Render for DeepStatefulTree {+ fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {+ use crate::{InteractiveElement as _, ParentElement as _, Styled as _, div, px};+ let depth = self.depth;+ div()+ .flex()+ .flex_wrap()+ .size_full()+ .children((0..self.items).map(move |item| {+ let mut element = div().id(("leaf", item as u64)).size(px(2.));+ for level in (0..depth).rev() {+ element = div()+ .id(("some-container-element", level as u64))+ .child(element);+ }+ element.id(("item", item as u64)).size(px(4.))+ }))+ }+ }++ /// Frame cost of a tree of stateful elements: every one of them builds a+ /// `GlobalElementId` and looks its state up in two frames' maps.+ ///+ /// `cargo test -p gpui --release --lib global_element_id_tests::frame_cost -- --ignored --nocapture`+ #[crate::test]+ #[ignore = "prints timings; run by hand"]+ fn frame_cost(cx: &mut crate::TestAppContext) {+ use crate::AppContext as _;+ for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {+ let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });+ let window = crate::AnyWindowHandle::from(window);+ let mut frame = |cx: &mut crate::TestAppContext| {+ cx.update_window(window, |_, window, cx| {+ window.refresh();+ let started = std::time::Instant::now();+ window.draw(cx).clear(cx);+ started.elapsed()+ })+ .unwrap()+ };+ for _ in 0..5 {+ frame(cx);+ }+ let mut samples: Vec<_> = (0..40).map(|_| frame(cx)).collect();+ samples.sort();+ let median = samples[samples.len() / 2];+ let stateful = items * (depth + 2);+ eprintln!(+ "{items} items x {depth} deep ({stateful} stateful elements): median frame {:.2} ms, {:.0} ns per stateful element",+ median.as_secs_f64() * 1e3,+ median.as_nanos() as f64 / stateful as f64,+ );+ }+ }++ /// `cargo test -p gpui --release --lib global_element_id_tests::hash_cost -- --ignored --nocapture`+ #[test]+ #[ignore = "prints timings; run by hand"]+ fn hash_cost() {+ let ids = path(11, 7);+ let id = GlobalElementId::new(&ids);+ let n = 1_000_000u64;+ let mut acc = 0u64;+ let started = std::time::Instant::now();+ for _ in 0..n {+ acc ^= fx_hash(&std::hint::black_box(ids.as_slice()));+ }+ let walk = started.elapsed();+ let started = std::time::Instant::now();+ for _ in 0..n {+ acc ^= fx_hash(std::hint::black_box(&id));+ }+ let cached = started.elapsed();+ let started = std::time::Instant::now();+ for _ in 0..n {+ acc ^= GlobalElementId::new(std::hint::black_box(&ids)).hash;+ }+ let build = started.elapsed();+ eprintln!(+ "12-deep path: hash by walking ids {:.1} ns, cached {:.1} ns, build (clone + hash once) {:.1} ns [{acc}]",+ walk.as_nanos() as f64 / n as f64,+ cached.as_nanos() as f64 / n as f64,+ build.as_nanos() as f64 / n as f64,+ );+ }+}diff --git a/crates/gpui/src/randomized_element_tree.rs b/crates/gpui/src/randomized_element_tree.rsindex 1366317bc6e..0325769068d 100644--- a/crates/gpui/src/randomized_element_tree.rs+++ b/crates/gpui/src/randomized_element_tree.rs@@ -1446,7 +1446,7 @@ mod tests {.element_states.keys().filter_map(|(global_id, _)| {- let ElementId::NamedInteger(name, element_id) = global_id.0.last()? else {+ let ElementId::NamedInteger(name, element_id) = global_id.last()? else {return None;};(name.as_ref() == "randomized-element").then_some(*element_id)diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rsindex 259a451ab16..e892ea2afef 100644--- a/crates/gpui/src/window.rs+++ b/crates/gpui/src/window.rs@@ -970,11 +970,59 @@ pub(crate) struct TooltipRequest {tooltip: AnyTooltip,}+/// The ids of the elements being drawn, root first, with the hash of every+/// prefix alongside: a [`GlobalElementId`] for the current element is then+/// the ids cloned out and the hash on top of the stack, without walking the+/// path — the ids of every ancestor, string names byte by byte — for each+/// element on every frame.+#[derive(Clone, Default)]+pub(crate) struct ElementIdStack {+ ids: SmallVec<[ElementId; 32]>,+ hashes: SmallVec<[u64; 32]>,+}++impl ElementIdStack {+ pub(crate) fn push(&mut self, id: ElementId) {+ self.hashes.push(crate::extend_path_hash(self.hash(), &id));+ self.ids.push(id);+ }++ pub(crate) fn pop(&mut self) -> Option<ElementId> {+ self.hashes.pop();+ self.ids.pop()+ }++ pub(crate) fn clear(&mut self) {+ self.ids.clear();+ self.hashes.clear();+ }++ /// The hash of the whole path on the stack.+ fn hash(&self) -> u64 {+ self.hashes+ .last()+ .copied()+ .unwrap_or(crate::EMPTY_PATH_HASH)+ }++ pub(crate) fn global_id(&self) -> GlobalElementId {+ GlobalElementId::with_hash(&self.ids, self.hash())+ }+}++impl std::ops::Deref for ElementIdStack {+ type Target = [ElementId];++ fn deref(&self) -> &Self::Target {+ &self.ids+ }+}+pub(crate) struct DeferredDraw {current_view: EntityId,priority: usize,parent_node: DispatchNodeId,- element_id_stack: SmallVec<[ElementId; 32]>,+ element_id_stack: ElementIdStack,text_style_stack: Vec<TextStyleRefinement>,content_mask: Option<ContentMask<Pixels>>,rem_size: Pixels,@@ -1183,7 +1231,7 @@ pub struct Window {pub(crate) viewport_size: Size<Pixels>,layout_engine: Option<TaffyLayoutEngine>,pub(crate) root: Option<AnyView>,- pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,+ pub(crate) element_id_stack: ElementIdStack,pub(crate) text_style_stack: Vec<TextStyleRefinement>,pub(crate) rendered_entity_stack: Vec<EntityId>,pub(crate) element_offset_stack: Vec<Point<Pixels>>,@@ -2078,7 +2126,7 @@ impl Window {viewport_size: content_size,layout_engine: Some(TaffyLayoutEngine::new()),root: None,- element_id_stack: SmallVec::default(),+ element_id_stack: ElementIdStack::default(),text_style_stack: Vec::new(),rendered_entity_stack: Vec::new(),element_offset_stack: Vec::new(),@@ -3004,7 +3052,7 @@ impl Window {f: impl FnOnce(&GlobalElementId, &mut Self) -> R,) -> R {self.with_id(element_id, |this| {- let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));+ let global_id = this.element_id_stack.global_id();f(&global_id, this)})