From f3ddbcf1a8e5e032988269e10a70cd1ecdad5bc5 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Thu, 13 Feb 2025 11:49:15 +0000 Subject: [PATCH] =?UTF-8?q?refactor:=20=E2=9A=A1=EF=B8=8F=20Speed=20up=20f?= =?UTF-8?q?unction=20`=5Ftruncate=5Fvalue`=20by=2045%=20(`main`)=20(#6334)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ⚡️ Speed up function `_truncate_value` by 45% in PR #6323 (`test-smol`) To optimize the Python program for faster performance, we should make a few adjustments. Specifically, the use of multiple `isinstance` checks and logical conditioning can be streamlined to reduce the runtime overhead. Here's the optimized version of the program. ### Explanation. 1. **Order and Conditions**: We adjusted the order to check the limit first. This way, we only perform the `isinstance` check if the limit is set, thereby potentially reducing the number of checks needed. 2. **Combined Types**: Instead of using `isinstance(value, list | tuple)`, which uses the `|` operator for a union type, we use the more traditional tuple form `isinstance(value, (list, tuple))`. This makes it explicit that we’re checking against multiple types and can be a bit faster. These changes should result in slight performance improvements by reducing the number of checks and short-circuiting earlier. Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com> Co-authored-by: Gabriel Luiz Freitas Almeida --- src/backend/base/langflow/serialization/serialization.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/backend/base/langflow/serialization/serialization.py b/src/backend/base/langflow/serialization/serialization.py index d94a166ae..3a8c47b57 100644 --- a/src/backend/base/langflow/serialization/serialization.py +++ b/src/backend/base/langflow/serialization/serialization.py @@ -109,9 +109,9 @@ def _serialize_instance(obj: Any, *_) -> str: def _truncate_value(value: Any, max_length: int | None, max_items: int | None) -> Any: """Truncate value based on its type and provided limits.""" - if isinstance(value, str) and max_length is not None and len(value) > max_length: + if max_length is not None and isinstance(value, str) and len(value) > max_length: return value[:max_length] - if isinstance(value, list | tuple) and max_items is not None and len(value) > max_items: + if max_items is not None and isinstance(value, (list, tuple)) and len(value) > max_items: return value[:max_items] return value