From 1d061cee9c3fda8c48c096206e11f6e153ce263c Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Tue, 21 Oct 2025 23:28:49 +0000 Subject: [PATCH] Optimize get_api_version The optimization moves the dictionary `int_version` from being created inside the function to a module-level constant `_INT_VERSION`. This eliminates the repeated dictionary creation overhead that was consuming ~68% of the original function's runtime (lines creating the dictionary took 27% + 19.9% + 21.3% = 68.2% of total time). **Key changes:** - Dictionary is now created once at module import time instead of on every function call - Function body reduced from 4 operations to 1 dictionary lookup **Why this leads to speedup:** - Dictionary creation in Python involves memory allocation and hash table initialization - The profiler shows 6,143 function calls were creating identical dictionaries repeatedly - Moving to module scope eliminates this redundant work, keeping only the fast dictionary lookup operation **Performance characteristics:** - Consistent ~20-44% speedup across all test cases - Larger improvements for simple cases (empty strings: 63.6% faster) - Even large-scale tests with 500-1000 calls show 18-25% improvements - Benefits scale linearly with call frequency since dictionary creation overhead is completely eliminated This is a classic example of hoisting invariant computations out of frequently-called functions. --- src/cohere/aws_client.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/cohere/aws_client.py b/src/cohere/aws_client.py index 8aea9d15c..47c5cdea8 100644 --- a/src/cohere/aws_client.py +++ b/src/cohere/aws_client.py @@ -14,6 +14,11 @@ from .manually_maintained.lazy_aws_deps import lazy_boto3, lazy_botocore from .client_v2 import ClientV2 +_INT_VERSION = { + "v1": 1, + "v2": 2, +} + class AwsClient(Client): def __init__( self, @@ -285,9 +290,4 @@ def get_url( def get_api_version(*, version: str): - int_version = { - "v1": 1, - "v2": 2, - } - - return int_version.get(version, 1) \ No newline at end of file + return _INT_VERSION.get(version, 1) \ No newline at end of file