Skip to content

⚡️ Speed up method ResourceTemplate.matches by 139%#3

Open
codeflash-ai[bot] wants to merge 1 commit into
mainfrom
codeflash/optimize-ResourceTemplate.matches-ma2xdwmi
Open

⚡️ Speed up method ResourceTemplate.matches by 139%#3
codeflash-ai[bot] wants to merge 1 commit into
mainfrom
codeflash/optimize-ResourceTemplate.matches-ma2xdwmi

Conversation

@codeflash-ai
Copy link
Copy Markdown

@codeflash-ai codeflash-ai Bot commented Apr 29, 2025

📄 139% (1.39x) speedup for ResourceTemplate.matches in src/mcp/server/fastmcp/resources/templates.py

⏱️ Runtime : 50.4 microseconds 21.1 microseconds (best of 132 runs)

📝 Explanation and details

Here’s the optimized version of your program, using Python 3.11+ features, and your profiling results. The hottest spot is re.match (almost all the runtime), and the second hottest is the on-the-fly string replacement for the regex pattern.

Optimizations:

  • Precompile the regex: Instead of reconstructing and recompiling the regex every call, compile it once and cache on the instance (in __init__). This eliminates repeated regex compilation and pattern construction.
  • Efficient pattern construction: Instead of chained replace() calls, use re.sub for more reliable and faster parsing, especially for many parameters.
  • Thread-safe cache: Since Pydantic models can be copied or mutated, cache the regex as a private attribute (_compiled_uri_re), initializing it once per instance.

Code (with comments preserved):

Key points:

  • Pattern is only constructed and compiled once per instance, not every call.
  • Matching now only needs regex.match, not string ops or compile.
  • Fully backward compatible (return values are identical).

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 30 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests Details
from __future__ import annotations

import re
from collections.abc import Callable
from typing import Any

# imports
import pytest  # used for our unit tests
from pydantic import BaseModel, Field
from src.mcp.server.fastmcp.resources.templates import ResourceTemplate

# unit tests

def test_simple_template_with_one_parameter():
    """Test simple template with one parameter."""
    template = ResourceTemplate(uri_template="weather://{city}/current", name="Weather", description=None, fn=lambda: None, parameters={})
    codeflash_output = template.matches("weather://London/current")
    codeflash_output = template.matches("weather://NewYork/current")





def test_invalid_uri_format():
    """Test invalid URI format."""
    template = ResourceTemplate(uri_template="weather://{city}/current", name="Weather", description=None, fn=lambda: None, parameters={})
    codeflash_output = template.matches("weather:/London/current")
    codeflash_output = template.matches("weather://London/current/extra")


def test_large_uri_performance():
    """Test performance with large URI."""
    template = ResourceTemplate(uri_template="data://{category}/{subcategory}/{item}/details", name="Data", description=None, fn=lambda: None, parameters={})
    large_uri = "data://" + "/".join(["category" + str(i) for i in range(100)]) + "/details"
    expected_result = {f"category{i}": f"category{i}" for i in range(100)}
    codeflash_output = template.matches(large_uri)

def test_completely_different_uri():
    """Test completely different URI."""
    template = ResourceTemplate(uri_template="weather://{city}/current", name="Weather", description=None, fn=lambda: None, parameters={})
    codeflash_output = template.matches("sports://football/match")

def test_similar_but_non_matching_uris():
    """Test similar but non-matching URIs."""
    template = ResourceTemplate(uri_template="weather://{city}/current", name="Weather", description=None, fn=lambda: None, parameters={})
    codeflash_output = template.matches("weather://London/forecast")
    codeflash_output = template.matches("weather://London")
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

from __future__ import annotations

import re
from collections.abc import Callable
from typing import Any

# imports
import pytest  # used for our unit tests
from pydantic import BaseModel, Field
from src.mcp.server.fastmcp.resources.templates import ResourceTemplate

# unit tests















from src.mcp.server.fastmcp.resources.templates import ResourceTemplate

To edit these changes git checkout codeflash/optimize-ResourceTemplate.matches-ma2xdwmi and push.

Codeflash

Here’s the optimized version of your program, using Python 3.11+ features, and your profiling results. The hottest spot is `re.match` (almost all the runtime), and the second hottest is the on-the-fly string replacement for the regex pattern.

**Optimizations:**
- **Precompile the regex**: Instead of reconstructing and recompiling the regex every call, compile it once and cache on the instance (in `__init__`). This eliminates repeated regex compilation and pattern construction.
- **Efficient pattern construction**: Instead of chained `replace()` calls, use `re.sub` for more reliable and faster parsing, especially for many parameters.
- **Thread-safe cache**: Since Pydantic models can be copied or mutated, cache the regex as a private attribute (`_compiled_uri_re`), initializing it once per instance.

**Code (with comments preserved):**



**Key points:**
- Pattern is only constructed and compiled once per instance, not every call.
- Matching now only needs `regex.match`, not string ops or compile.
- Fully backward compatible (return values are identical).
@codeflash-ai codeflash-ai Bot added the ⚡️ codeflash Optimization PR opened by Codeflash AI label Apr 29, 2025
@codeflash-ai codeflash-ai Bot requested a review from Saga4 April 29, 2025 19:54
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.

0 participants