From 708d59a5073841fddba782ad3c1fac315e897cdf Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sun, 1 Nov 2026 21:54:17 -0700 Subject: [PATCH] [shape-plan] Cache the last shape plan looked up per face (#6550) hb_shape_plan_create_cached2() walks the face's plan list on every call. The list is never capped (by design, like the rest of the cache), so on a long-lived face that has accumulated many plans, repeatedly reshaping with a plan that sits deep in the list re-walks it each time. Add a one-entry per-face "last plan" cache: an atomic pointer to the most recently matched node, checked before the list walk and updated on hit and on insert. Plan nodes are never freed before the face, so a cached pointer stays valid; a stale or raced read just fails the key compare and falls through to the walk. The common single-plan case already hit on the first node (the list is front-prepended); this bounds the lookup for the many-plan case too. Uses hb_atomic_t::set_release(), added in #6549. Co-authored-by: Claude Opus 4.8 --- src/hb-face.hh | 4 ++++ src/hb-shape-plan.cc | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/src/hb-face.hh b/src/hb-face.hh index 77c243721..baa1a2e57 100644 --- a/src/hb-face.hh +++ b/src/hb-face.hh @@ -71,6 +71,10 @@ struct hb_face_t }; #ifndef HB_NO_SHAPER hb_atomic_t shape_plans; + /* One-entry cache of the last plan looked up, so repeated shaping with the + * same key hits without walking the list. Nodes are never freed before the + * face, so a cached pointer stays valid. */ + hb_atomic_t last_shape_plan; #endif hb_blob_t *reference_table (hb_tag_t tag) const diff --git a/src/hb-shape-plan.cc b/src/hb-shape-plan.cc index 8f5287918..e6a79f9b2 100644 --- a/src/hb-shape-plan.cc +++ b/src/hb-shape-plan.cc @@ -567,10 +567,18 @@ retry: shaper_list)) return hb_shape_plan_get_empty (); + hb_face_t::plan_node_t *cached = face->last_shape_plan.get_acquire (); + if (cached && cached->shape_plan->key.equal (&key)) + { + DEBUG_MSG_FUNC (SHAPE_PLAN, cached->shape_plan, "fulfilled from last-plan cache"); + return hb_shape_plan_reference (cached->shape_plan); + } + for (hb_face_t::plan_node_t *node = cached_plan_nodes; node; node = node->next) if (node->shape_plan->key.equal (&key)) { DEBUG_MSG_FUNC (SHAPE_PLAN, node->shape_plan, "fulfilled from cache"); + face->last_shape_plan.set_release (node); return hb_shape_plan_reference (node->shape_plan); } } @@ -597,6 +605,7 @@ retry: goto retry; } DEBUG_MSG_FUNC (SHAPE_PLAN, shape_plan, "inserted into cache"); + face->last_shape_plan.set_release (node); return hb_shape_plan_reference (shape_plan); }