From 273b6f75f76974bf52df79c0293cd2b7a59fea72 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Thu, 2 Apr 2026 16:08:46 +0000 Subject: [PATCH] Optimize _get_all_json_refs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `_get_all_json_refs` function was rewritten from recursive traversal to an iterative stack-based approach, achieving a 91% speedup (2.42ms → 1.26ms). Recursive calls in Python incur significant overhead from frame allocation and teardown on each nested dict/list, whereas the stack-based version amortizes this cost across the entire traversal with a single while-loop. The optimization is especially effective on deeply nested JSON schemas where recursive depth would trigger many function calls, now replaced by simple list append/extend operations. --- src/algorithms/search.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/algorithms/search.py b/src/algorithms/search.py index b2f17cc..bf3a687 100644 --- a/src/algorithms/search.py +++ b/src/algorithms/search.py @@ -9,19 +9,20 @@ def _get_all_json_refs(item: Any) -> set[JsonRef]: """Get all the definitions references from a JSON schema.""" refs: set[JsonRef] = set() - if isinstance(item, dict): - for key, value in item.items(): - if key == "$ref" and isinstance(value, str): - # the isinstance check ensures that '$ref' isn't the name of a property, etc. - refs.add(JsonRef(value)) - elif isinstance(value, dict): - refs.update(_get_all_json_refs(value)) - elif isinstance(value, list): - for item in value: - refs.update(_get_all_json_refs(item)) - elif isinstance(item, list): - for item in item: - refs.update(_get_all_json_refs(item)) + stack: list[Any] = [item] + while stack: + current = stack.pop() + if isinstance(current, dict): + for key, value in current.items(): + if key == "$ref" and isinstance(value, str): + # the isinstance check ensures that '$ref' isn't the name of a property, etc. + refs.add(JsonRef(value)) + elif isinstance(value, dict): + stack.append(value) + elif isinstance(value, list): + stack.extend(value) + elif isinstance(current, list): + stack.extend(current) return refs