Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Nov 14, 2025

📄 43% (0.43x) speedup for bitmart.custom_parse_balance in python/ccxt/async_support/bitmart.py

⏱️ Runtime : 49.4 milliseconds 34.6 milliseconds (best of 27 runs)

📝 Explanation and details

The optimized code achieves a 42% speedup by eliminating function call overhead and optimizing dictionary lookups in hot-path methods. The key optimizations focus on the most frequently called methods identified by the profiler:

What was optimized:

  1. Fast-path dictionary lookups: safe_string, safe_string_2, safe_string_n, safe_dict, and safe_list now use direct dict.get() calls for the common case where the input is a dictionary, avoiding the expensive Exchange.key_exists() machinery that includes type checking and exception handling.

  2. Inlined balance processing: The safe_balance method eliminates repeated self.safe_string() calls by directly accessing dictionary values with dict.get(), reducing function call overhead in the tight loop that processes each currency code.

  3. Early exit optimization: safe_currency_code adds a fast check for non-None inputs to avoid unnecessary function calls in the common case.

Why this leads to speedup:

  • Reduced function call overhead: The original code made ~49,609 calls to safe_string with 1232ns per call. The optimized version reduces this significantly by inlining dictionary access.
  • Faster dictionary access: Using dict.get() directly instead of Exchange.key_exists() eliminates isinstance checks, exception handling, and multiple function calls.
  • Loop optimization: In safe_balance, the most expensive method (22.5% of runtime), inlining dictionary access eliminates thousands of function calls per balance processing operation.

Test case performance:
The optimization excels across all test scenarios, with particularly strong gains on:

  • Large-scale tests (49-58% faster) where the loop optimizations compound
  • Edge cases with missing fields (33-47% faster) due to efficient None handling
  • Basic operations (14-29% faster) from reduced overhead

This optimization maintains identical behavior while dramatically improving performance for cryptocurrency exchange balance parsing, which is typically called frequently in trading applications.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 122 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
from copy import deepcopy

# imports
import pytest
from ccxt.async_support.bitmart import bitmart

# ------------------------------
# UNIT TESTS FOR custom_parse_balance
# ------------------------------

@pytest.fixture
def bitmart_instance():
    return bitmart()

# 1. Basic Test Cases

def test_basic_spot_balance(bitmart_instance):
    # Test a typical spot wallet response
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "1.23", "frozen": "0.77"},
                {"currency": "ETH", "available": "2.34", "frozen": "0.66"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 49.5μs -> 39.6μs (25.0% faster)

def test_basic_swap_balance(bitmart_instance):
    # Test swap wallet response
    response = {
        "data": [
            {"currency": "USDT", "available_balance": "100.5", "frozen_balance": "10.2"},
            {"currency": "BTC", "available_balance": "0.5", "frozen_balance": "0.1"}
        ]
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 49.2μs -> 38.6μs (27.7% faster)

def test_basic_margin_balance(bitmart_instance):
    # Margin wallet with base/quote
    response = {
        "data": {
            "symbols": [
                {
                    "symbol": "BTC_USDT",
                    "base": {
                        "currency": "BTC",
                        "available": "1.0",
                        "frozen": "0.5",
                        "total_asset": "1.5",
                        "borrow_unpaid": "0.2",
                        "interest_unpaid": "0.05"
                    },
                    "quote": {
                        "currency": "USDT",
                        "available": "100.0",
                        "frozen": "25.0",
                        "total_asset": "125.0",
                        "borrow_unpaid": "10.0",
                        "interest_unpaid": "2.0"
                    }
                }
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 63.6μs -> 55.6μs (14.4% faster)
    margin_bal = result["BTC/USDT"]

def test_basic_coin_code_override(bitmart_instance):
    # Test coin_code overrides currency/id
    response = {
        "data": {
            "wallet": [
                {"id": "BTC", "coin_code": "XBT", "available": "2.0", "frozen": "1.0"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 35.9μs -> 29.2μs (23.2% faster)

# 2. Edge Test Cases

def test_missing_fields(bitmart_instance):
    # Missing 'frozen' and 'available' fields
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": None, "frozen": "1.0"},
                {"currency": "ETH", "available": "2.0", "frozen": None}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 34.1μs -> 24.3μs (40.5% faster)

def test_empty_wallet_list(bitmart_instance):
    # Empty wallet list
    response = {"data": {"wallet": []}}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 8.88μs -> 6.06μs (46.6% faster)

def test_no_data_key(bitmart_instance):
    # No 'data' key in response
    response = {}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 8.36μs -> 6.12μs (36.6% faster)

def test_fallback_to_id(bitmart_instance):
    # Only 'id' provided, no 'currency'
    response = {
        "data": {
            "wallet": [
                {"id": "usdt", "available": "10", "frozen": "2"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 35.0μs -> 28.3μs (23.7% faster)

def test_margin_missing_base_quote(bitmart_instance):
    # Margin symbol missing base/quote dicts
    response = {
        "data": {
            "symbols": [
                {"symbol": "BTC_USDT"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 43.6μs -> 32.8μs (33.1% faster)
    margin_bal = result["BTC/USDT"]

def test_margin_missing_debt_interest(bitmart_instance):
    # Margin symbol missing debt/interest
    response = {
        "data": {
            "symbols": [
                {
                    "symbol": "BTC_USDT",
                    "base": {
                        "currency": "BTC",
                        "available": "1.0",
                        "frozen": "0.5",
                        "total_asset": "1.5"
                    },
                    "quote": {
                        "currency": "USDT",
                        "available": "100.0",
                        "frozen": "25.0",
                        "total_asset": "125.0"
                    }
                }
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 47.8μs -> 38.7μs (23.7% faster)
    margin_bal = result["BTC/USDT"]

def test_swap_with_missing_fields(bitmart_instance):
    # Swap wallet with missing balances
    response = {
        "data": [
            {"currency": "USDT"},
            {"currency": "BTC", "available_balance": "0.5"}
        ]
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 33.4μs -> 23.5μs (41.9% faster)

def test_nonstandard_keys(bitmart_instance):
    # Test with 'unAvailable' and 'frozen_balance'
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "1.5", "unAvailable": "0.5"},
                {"currency": "ETH", "available": "2.5", "frozen_balance": "1.5"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 48.7μs -> 39.1μs (24.6% faster)

def test_currency_case_insensitivity(bitmart_instance):
    # Lowercase currency
    response = {
        "data": {
            "wallet": [
                {"currency": "btc", "available": "1.0", "frozen": "0.5"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 36.1μs -> 28.7μs (25.8% faster)

# 3. Large Scale Test Cases

def test_large_wallet_list(bitmart_instance):
    # Test with 1000 wallet entries
    wallet_entries = []
    for i in range(1, 1001):
        wallet_entries.append({
            "currency": f"COIN{i}",
            "available": str(i),
            "frozen": str(i / 2)
        })
    response = {"data": {"wallet": wallet_entries}}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 8.61ms -> 5.77ms (49.1% faster)

def test_large_margin_symbols(bitmart_instance):
    # 500 margin symbols, each with base/quote
    symbols = []
    for i in range(1, 501):
        symbols.append({
            "symbol": f"BASE{i}_QUOTE{i}",
            "base": {
                "currency": f"BASE{i}",
                "available": str(i),
                "frozen": str(i / 2),
                "total_asset": str(i * 1.5),
                "borrow_unpaid": str(i * 0.1),
                "interest_unpaid": str(i * 0.01)
            },
            "quote": {
                "currency": f"QUOTE{i}",
                "available": str(i * 2),
                "frozen": str(i),
                "total_asset": str(i * 3),
                "borrow_unpaid": str(i * 0.2),
                "interest_unpaid": str(i * 0.02)
            }
        })
    response = {"data": {"symbols": symbols}}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 15.1ms -> 11.3ms (33.6% faster)
    bal = result["BASE1/QUOTE1"]
    # Check last
    bal_last = result["BASE500/QUOTE500"]

def test_large_swap_wallet(bitmart_instance):
    # 1000 swap wallet entries
    wallet_entries = []
    for i in range(1, 1001):
        wallet_entries.append({
            "currency": f"SWAP{i}",
            "available_balance": str(i * 10),
            "frozen_balance": str(i)
        })
    response = {"data": wallet_entries}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 8.40ms -> 5.33ms (57.7% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
import pytest
from ccxt.async_support.bitmart import bitmart

# function to test
# (see above for definition of bitmart.custom_parse_balance)

# Helper: instantiate the bitmart class
@pytest.fixture
def bitmart_instance():
    return bitmart({})

# ----------------------------- BASIC TEST CASES -----------------------------

def test_spot_basic_single_currency(bitmart_instance):
    # Basic: Spot wallet, single currency
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "0.5", "frozen": "0.1", "total": "0.6"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 35.4μs -> 27.9μs (26.7% faster)

def test_spot_basic_multiple_currencies(bitmart_instance):
    # Basic: Spot wallet, multiple currencies
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "1", "frozen": "0", "total": "1"},
                {"currency": "ETH", "available": "2.5", "frozen": "0.5", "total": "3.0"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 48.6μs -> 38.7μs (25.7% faster)

def test_swap_basic_single_currency(bitmart_instance):
    # Basic: Swap wallet, single currency
    response = {
        "data": [
            {"currency": "USDT", "available_balance": "100", "frozen_balance": "10", "total": "110"}
        ]
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 36.8μs -> 29.1μs (26.2% faster)

def test_margin_basic_single_symbol(bitmart_instance):
    # Basic: Margin wallet, single symbol
    response = {
        "data": {
            "symbols": [
                {
                    "symbol": "BTC_USDT",
                    "base": {
                        "currency": "BTC",
                        "available": "0.2",
                        "frozen": "0.05",
                        "total_asset": "0.25",
                        "borrow_unpaid": "0.01",
                        "interest_unpaid": "0.001"
                    },
                    "quote": {
                        "currency": "USDT",
                        "available": "100",
                        "frozen": "10",
                        "total_asset": "110",
                        "borrow_unpaid": "5",
                        "interest_unpaid": "0.5"
                    }
                }
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 63.2μs -> 55.2μs (14.5% faster)
    margin_bal = result["BTC/USDT"]

# ----------------------------- EDGE TEST CASES ------------------------------

def test_spot_missing_fields(bitmart_instance):
    # Edge: Missing fields (no 'frozen', no 'total')
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "0.5"}  # missing 'frozen' and 'total'
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 25.2μs -> 18.3μs (37.4% faster)

def test_spot_zero_balances(bitmart_instance):
    # Edge: Zero balances
    response = {
        "data": {
            "wallet": [
                {"currency": "ETH", "available": "0", "frozen": "0", "total": "0"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 34.6μs -> 26.9μs (28.7% faster)

def test_spot_unusual_currency_code(bitmart_instance):
    # Edge: Unusual currency code, e.g. XBT (should be normalized to BTC)
    response = {
        "data": {
            "wallet": [
                {"currency": "XBT", "available": "1", "frozen": "0", "total": "1"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 34.9μs -> 27.2μs (28.0% faster)

def test_swap_coin_code_field(bitmart_instance):
    # Edge: Use 'coin_code' field instead of 'currency'
    response = {
        "data": [
            {"coin_code": "ETH", "available_balance": "2", "frozen_balance": "1", "total": "3"}
        ]
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 34.6μs -> 26.8μs (28.8% faster)

def test_margin_missing_interest(bitmart_instance):
    # Edge: Margin with missing interest_unpaid
    response = {
        "data": {
            "symbols": [
                {
                    "symbol": "ETH_USDT",
                    "base": {
                        "currency": "ETH",
                        "available": "10",
                        "frozen": "2",
                        "total_asset": "12",
                        "borrow_unpaid": "0.5"
                        # missing interest_unpaid
                    },
                    "quote": {
                        "currency": "USDT",
                        "available": "100",
                        "frozen": "0",
                        "total_asset": "100",
                        "borrow_unpaid": "0",
                        "interest_unpaid": "0"
                    }
                }
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 55.9μs -> 48.2μs (15.9% faster)
    margin_bal = result["ETH/USDT"]

def test_margin_missing_symbol(bitmart_instance):
    # Edge: Margin with missing symbol field
    response = {
        "data": {
            "symbols": [
                {
                    "base": {
                        "currency": "BTC",
                        "available": "1",
                        "frozen": "0",
                        "total_asset": "1",
                        "borrow_unpaid": "0",
                        "interest_unpaid": "0"
                    },
                    "quote": {
                        "currency": "USDT",
                        "available": "50",
                        "frozen": "0",
                        "total_asset": "50",
                        "borrow_unpaid": "0",
                        "interest_unpaid": "0"
                    }
                }
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 51.1μs -> 42.5μs (20.1% faster)

def test_empty_wallet(bitmart_instance):
    # Edge: Empty wallet list
    response = {"data": {"wallet": []}}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 8.91μs -> 6.08μs (46.5% faster)

def test_no_data_field(bitmart_instance):
    # Edge: No 'data' field at all
    response = {}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 8.33μs -> 6.25μs (33.3% faster)

def test_swap_unavailable_field(bitmart_instance):
    # Edge: Swap wallet with 'unAvailable' field for used
    response = {
        "data": [
            {"currency": "USDT", "available_balance": "100", "unAvailable": "20"}
        ]
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 36.4μs -> 29.5μs (23.4% faster)

def test_spot_frozen_balance_field(bitmart_instance):
    # Edge: Spot wallet with 'frozen_balance' field for used
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "1", "frozen_balance": "0.5", "total": "1.5"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 36.9μs -> 29.8μs (23.9% faster)

# -------------------------- LARGE SCALE TEST CASES --------------------------

def test_spot_large_scale(bitmart_instance):
    # Large scale: Spot wallet with 500 currencies
    currencies = [f"C{i}" for i in range(500)]
    wallet = [{"currency": c, "available": str(i), "frozen": str(i/2), "total": str(i*1.5)} for i, c in enumerate(currencies)]
    response = {"data": {"wallet": wallet}}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 4.31ms -> 2.88ms (49.8% faster)
    for i, c in enumerate(currencies):
        pass

def test_swap_large_scale(bitmart_instance):
    # Large scale: Swap wallet with 500 currencies
    currencies = [f"SWAP{i}" for i in range(500)]
    wallet = [{"currency": c, "available_balance": str(i), "frozen_balance": str(i/10), "total": str(i*1.1)} for i, c in enumerate(currencies)]
    response = {"data": wallet}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 4.40ms -> 2.86ms (53.8% faster)
    for i, c in enumerate(currencies):
        pass

def test_margin_large_scale(bitmart_instance):
    # Large scale: Margin wallet with 250 symbols, each with 2 currencies
    symbols = []
    for i in range(250):
        symbols.append({
            "symbol": f"C{i}_C{i+1}",
            "base": {
                "currency": f"C{i}",
                "available": str(i),
                "frozen": str(i/2),
                "total_asset": str(i*1.5),
                "borrow_unpaid": str(i/10),
                "interest_unpaid": str(i/100)
            },
            "quote": {
                "currency": f"C{i+1}",
                "available": str(i+1),
                "frozen": str((i+1)/2),
                "total_asset": str((i+1)*1.5),
                "borrow_unpaid": str((i+1)/10),
                "interest_unpaid": str((i+1)/100)
            }
        })
    response = {"data": {"symbols": symbols}}
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 7.19ms -> 5.37ms (33.7% faster)
    for i in range(250):
        symbol = f"C{i}/C{i+1}"
        base = result[symbol][f"C{i}"]
        quote = result[symbol][f"C{i+1}"]

# ------------------------ DETERMINISM AND CONSISTENCY -----------------------

def test_spot_determinism(bitmart_instance):
    # Determinism: Same input always yields same output
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "1", "frozen": "0.5", "total": "1.5"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result1 = codeflash_output # 36.8μs -> 29.9μs (23.2% faster)
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result2 = codeflash_output # 18.2μs -> 14.7μs (24.5% faster)

def test_margin_determinism(bitmart_instance):
    # Determinism: Margin wallet
    response = {
        "data": {
            "symbols": [
                {
                    "symbol": "BTC_USDT",
                    "base": {
                        "currency": "BTC",
                        "available": "0.2",
                        "frozen": "0.05",
                        "total_asset": "0.25",
                        "borrow_unpaid": "0.01",
                        "interest_unpaid": "0.001"
                    },
                    "quote": {
                        "currency": "USDT",
                        "available": "100",
                        "frozen": "10",
                        "total_asset": "110",
                        "borrow_unpaid": "5",
                        "interest_unpaid": "0.5"
                    }
                }
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result1 = codeflash_output # 63.4μs -> 55.1μs (15.0% faster)
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result2 = codeflash_output # 39.1μs -> 30.6μs (27.7% faster)

# ---------------------------- ERROR HANDLING TESTS --------------------------



def test_margin_symbol_normalization(bitmart_instance):
    # Margin symbol normalization (underscore to slash)
    response = {
        "data": {
            "symbols": [
                {
                    "symbol": "LTC_ETH",
                    "base": {
                        "currency": "LTC",
                        "available": "5",
                        "frozen": "1",
                        "total_asset": "6",
                        "borrow_unpaid": "0.1",
                        "interest_unpaid": "0.01"
                    },
                    "quote": {
                        "currency": "ETH",
                        "available": "10",
                        "frozen": "2",
                        "total_asset": "12",
                        "borrow_unpaid": "0.2",
                        "interest_unpaid": "0.02"
                    }
                }
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "margin"); result = codeflash_output # 63.5μs -> 55.2μs (15.2% faster)

# ---------------------------- MISCELLANEOUS TESTS --------------------------

def test_spot_currency_id_fallback(bitmart_instance):
    # Spot wallet with 'id' instead of 'currency'
    response = {
        "data": {
            "wallet": [
                {"id": "USDT", "available": "100", "frozen": "10", "total": "110"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 36.4μs -> 28.6μs (27.1% faster)

def test_spot_multiple_used_fields(bitmart_instance):
    # Spot wallet with both 'frozen' and 'unAvailable'
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": "2", "frozen": "1", "unAvailable": "1.5", "total": "3"}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 36.9μs -> 29.3μs (26.1% faster)

def test_swap_multiple_used_fields(bitmart_instance):
    # Swap wallet with both 'frozen_balance' and 'unAvailable'
    response = {
        "data": [
            {"currency": "BTC", "available_balance": "10", "frozen_balance": "2", "unAvailable": "3", "total": "15"}
        ]
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "swap"); result = codeflash_output # 35.5μs -> 28.0μs (27.0% faster)

def test_spot_non_string_numbers(bitmart_instance):
    # Spot wallet with numeric values (not strings)
    response = {
        "data": {
            "wallet": [
                {"currency": "BTC", "available": 1, "frozen": 0.5, "total": 1.5}
            ]
        }
    }
    codeflash_output = bitmart_instance.custom_parse_balance(response, "spot"); result = codeflash_output # 39.7μs -> 32.1μs (23.6% faster)
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

To edit these changes git checkout codeflash/optimize-bitmart.custom_parse_balance-mhz3aqxn and push.

Codeflash

The optimized code achieves a **42% speedup** by eliminating function call overhead and optimizing dictionary lookups in hot-path methods. The key optimizations focus on the most frequently called methods identified by the profiler:

**What was optimized:**
1. **Fast-path dictionary lookups**: `safe_string`, `safe_string_2`, `safe_string_n`, `safe_dict`, and `safe_list` now use direct `dict.get()` calls for the common case where the input is a dictionary, avoiding the expensive `Exchange.key_exists()` machinery that includes type checking and exception handling.

2. **Inlined balance processing**: The `safe_balance` method eliminates repeated `self.safe_string()` calls by directly accessing dictionary values with `dict.get()`, reducing function call overhead in the tight loop that processes each currency code.

3. **Early exit optimization**: `safe_currency_code` adds a fast check for non-None inputs to avoid unnecessary function calls in the common case.

**Why this leads to speedup:**
- **Reduced function call overhead**: The original code made ~49,609 calls to `safe_string` with 1232ns per call. The optimized version reduces this significantly by inlining dictionary access.
- **Faster dictionary access**: Using `dict.get()` directly instead of `Exchange.key_exists()` eliminates isinstance checks, exception handling, and multiple function calls.
- **Loop optimization**: In `safe_balance`, the most expensive method (22.5% of runtime), inlining dictionary access eliminates thousands of function calls per balance processing operation.

**Test case performance:**
The optimization excels across all test scenarios, with particularly strong gains on:
- Large-scale tests (49-58% faster) where the loop optimizations compound
- Edge cases with missing fields (33-47% faster) due to efficient None handling
- Basic operations (14-29% faster) from reduced overhead

This optimization maintains identical behavior while dramatically improving performance for cryptocurrency exchange balance parsing, which is typically called frequently in trading applications.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 November 14, 2025 16:46
@codeflash-ai codeflash-ai bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Nov 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant