Skip to content

Commit fe53dd5

Browse files
committed
refactor: share LRU cache between compile() and search()
1 parent 3aab7af commit fe53dd5

File tree

1 file changed

+30
-16
lines changed

1 file changed

+30
-16
lines changed

jsonpath/jsonpath.py

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -570,9 +570,36 @@ def __rmatmul__(self, other):
570570
return False
571571

572572

573+
# Global cache with LRU eviction to prevent memory leaks
574+
_jsonpath_cache = OrderedDict()
575+
_CACHE_MAX_SIZE = 128
576+
577+
578+
def _get_cached_jsonpath(expr: str) -> JSONPath:
579+
"""Get or create a cached JSONPath instance.
580+
581+
Args:
582+
expr: JSONPath expression string
583+
584+
Returns:
585+
Cached or newly created JSONPath instance
586+
"""
587+
if expr in _jsonpath_cache:
588+
# Move to end (mark as recently used)
589+
_jsonpath_cache.move_to_end(expr)
590+
else:
591+
# Evict oldest if cache is full
592+
if len(_jsonpath_cache) >= _CACHE_MAX_SIZE:
593+
_jsonpath_cache.popitem(last=False) # Remove oldest (FIFO)
594+
_jsonpath_cache[expr] = JSONPath(expr)
595+
return _jsonpath_cache[expr]
596+
597+
573598
def compile(expr):
574599
"""Compile a JSONPath expression for reuse.
575600
601+
Returns a cached JSONPath instance when available, avoiding redundant parsing.
602+
576603
Args:
577604
expr: JSONPath expression string
578605
@@ -584,16 +611,11 @@ def compile(expr):
584611
>>> jp.parse(data1)
585612
>>> jp.parse(data2)
586613
"""
587-
return JSONPath(expr)
588-
589-
590-
# global cache with LRU eviction to prevent memory leaks
591-
_jsonpath_cache = OrderedDict()
592-
_CACHE_MAX_SIZE = 128
614+
return _get_cached_jsonpath(expr)
593615

594616

595617
def search(expr, data):
596-
"""Search JSON data using JSONPath expression with LRU caching.
618+
"""Search JSON data using JSONPath expression with caching.
597619
598620
Args:
599621
expr: JSONPath expression string
@@ -602,12 +624,4 @@ def search(expr, data):
602624
Returns:
603625
List of matched values
604626
"""
605-
if expr in _jsonpath_cache:
606-
# Move to end (mark as recently used)
607-
_jsonpath_cache.move_to_end(expr)
608-
else:
609-
# Evict oldest if cache is full
610-
if len(_jsonpath_cache) >= _CACHE_MAX_SIZE:
611-
_jsonpath_cache.popitem(last=False) # Remove oldest (FIFO)
612-
_jsonpath_cache[expr] = JSONPath(expr)
613-
return _jsonpath_cache[expr].parse(data)
627+
return _get_cached_jsonpath(expr).parse(data)

0 commit comments

Comments
 (0)