From 6eb83cf9b785d2da364e8f763df0ceadfa70900b Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Tue, 4 Nov 2025 21:38:27 +0000 Subject: [PATCH] Optimize ValkeyDB._format_timestamp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The optimization improves the `_format_timestamp` method by avoiding redundant timezone object creation for UTC timestamps. **Key Changes:** - Added a fast-path check `if timezone is None or timezone == "UTC"` that bypasses `pytz.timezone()` lookup - For UTC cases, uses `datetime.utcfromtimestamp()` directly with `pytz.UTC` instead of creating a timezone object via `pytz.timezone("UTC")` **Why This Is Faster:** - `pytz.timezone()` performs string lookup and timezone object instantiation, which is expensive (18.7% of original runtime) - `datetime.utcfromtimestamp()` is a direct C-level operation that's much faster than `datetime.fromtimestamp()` with timezone conversion - The UTC fast-path eliminates the timezone lookup entirely for the most common case **Performance Impact:** - Line profiler shows timezone lookup time reduced from 22,317ns to 6,318ns (72% reduction) - Overall method execution improved by 13% (70.7μs → 62.5μs) This optimization is particularly effective for applications that primarily work with UTC timestamps, which is common in distributed systems and APIs where UTC is the standard. --- mem0/vector_stores/valkey.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/mem0/vector_stores/valkey.py b/mem0/vector_stores/valkey.py index c4539dcd21..82a2e1adf4 100644 --- a/mem0/vector_stores/valkey.py +++ b/mem0/vector_stores/valkey.py @@ -527,7 +527,9 @@ def _format_timestamp(self, timestamp, timezone=None): str: The formatted timestamp. """ # Use UTC as default timezone if not specified - tz = pytz.timezone(timezone or "UTC") + if timezone is None or timezone == "UTC": + return datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC).isoformat(timespec="microseconds") + tz = pytz.timezone(timezone) return datetime.fromtimestamp(timestamp, tz=tz).isoformat(timespec="microseconds") def _process_document_fields(self, result, vector_id):