Skip to content

Conversation

@codeflash-ai
Copy link

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

📄 6% (0.06x) speedup for LocalUrlService.get_model_image_url in invokeai/app/services/urls/urls_default.py

⏱️ Runtime : 406 microseconds 385 microseconds (best of 193 runs)

📝 Explanation and details

The optimization precomputes the static URL prefix f"{self._base_url_v2}/models/i/" during initialization and stores it as self._model_image_url_prefix. This eliminates redundant string formatting operations in the frequently-called get_model_image_url method.

Key changes:

  • Added self._model_image_url_prefix = f"{self._base_url_v2}/models/i/" in __init__
  • Simplified the return statement to f"{self._model_image_url_prefix}{model_key}/image"

Why it's faster:
The original code performs two string operations per call: accessing self._base_url_v2 and formatting the entire URL template. The optimized version reduces this to a single string concatenation by reusing the precomputed prefix. This saves approximately 70ns per call (358.4ns → 287.8ns per hit), resulting in a 5% overall speedup.

Performance characteristics:

  • Best gains (5-32% faster): Empty model keys, whitespace-only keys, unicode base URLs, and scenarios with trailing slashes
  • Consistent improvements (2-8% faster): Most standard alphanumeric keys and varied base URLs
  • Minimal impact (0-2% slower): Very long strings and some unicode edge cases where string allocation overhead dominates

This optimization is particularly valuable for URL services that generate many model image URLs, as each call now performs less work with no behavioral changes.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 3281 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 2 Passed
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime

import pytest
from invokeai.app.services.urls.urls_default import LocalUrlService

function to test

Copied from the provided code block

class UrlServiceBase:
pass
from invokeai.app.services.urls.urls_default import LocalUrlService

unit tests

1. Basic Test Cases

def test_basic_alphanumeric_key():
# Test with a simple alphanumeric key
service = LocalUrlService()
codeflash_output = service.get_model_image_url("model123") # 611ns -> 595ns (2.69% faster)

def test_basic_with_custom_base_url_v2():
# Test with a custom base_url_v2
service = LocalUrlService(base_url_v2="custom/v2")
codeflash_output = service.get_model_image_url("abcDEF") # 598ns -> 573ns (4.36% faster)

def test_basic_with_special_characters():
# Test with model_key containing dashes and underscores
service = LocalUrlService()
codeflash_output = service.get_model_image_url("model-abc_DEF") # 528ns -> 553ns (4.52% slower)

def test_basic_with_numeric_key():
# Test with model_key as a number string
service = LocalUrlService()
codeflash_output = service.get_model_image_url("123456") # 549ns -> 526ns (4.37% faster)

2. Edge Test Cases

def test_edge_empty_model_key():
# Test with an empty model_key
service = LocalUrlService()
codeflash_output = service.get_model_image_url("") # 531ns -> 504ns (5.36% faster)

def test_edge_model_key_with_spaces():
# Test with model_key containing spaces
service = LocalUrlService()
codeflash_output = service.get_model_image_url("my model key") # 522ns -> 519ns (0.578% faster)

def test_edge_model_key_with_unicode():
# Test with model_key containing Unicode characters
service = LocalUrlService()
codeflash_output = service.get_model_image_url("模型123") # 845ns -> 849ns (0.471% slower)

def test_edge_model_key_with_url_reserved_chars():
# Test with model_key containing URL reserved characters
service = LocalUrlService()
reserved = ":/?#[]@!{report_table}'()*+,;="
codeflash_output = service.get_model_image_url(reserved) # 564ns -> 526ns (7.22% faster)

def test_edge_model_key_with_slashes():
# Test with model_key containing forward slashes (could break paths)
service = LocalUrlService()
key = "foo/bar/baz"
codeflash_output = service.get_model_image_url(key) # 558ns -> 519ns (7.51% faster)

def test_edge_model_key_with_backslashes():
# Test with model_key containing backslashes
service = LocalUrlService()
key = "foo\bar\baz"
codeflash_output = service.get_model_image_url(key) # 484ns -> 489ns (1.02% slower)

def test_edge_model_key_is_long_string():
# Test with a very long model_key
service = LocalUrlService()
long_key = "a" * 255
codeflash_output = service.get_model_image_url(long_key) # 616ns -> 582ns (5.84% faster)

def test_edge_base_url_v2_with_trailing_slash():
# Test with base_url_v2 having a trailing slash
service = LocalUrlService(base_url_v2="api/v2/")
codeflash_output = service.get_model_image_url("model123") # 501ns -> 478ns (4.81% faster)

def test_edge_base_url_v2_is_empty():
# Test with base_url_v2 as an empty string
service = LocalUrlService(base_url_v2="")
codeflash_output = service.get_model_image_url("model123") # 494ns -> 480ns (2.92% faster)

def test_edge_model_key_is_none_string():
# Test with model_key as the string "None"
service = LocalUrlService()
codeflash_output = service.get_model_image_url("None") # 529ns -> 517ns (2.32% faster)

def test_edge_model_key_is_whitespace():
# Test with model_key as whitespace only
service = LocalUrlService()
codeflash_output = service.get_model_image_url(" ") # 514ns -> 472ns (8.90% faster)

3. Large Scale Test Cases

def test_large_scale_many_unique_keys():
# Test with a large number of unique model_keys
service = LocalUrlService()
for i in range(1000):
key = f"model_{i}"
expected_url = f"api/v2/models/i/model_{i}/image"
codeflash_output = service.get_model_image_url(key) # 183μs -> 172μs (6.25% faster)

def test_large_scale_long_base_url_v2_and_key():
# Test with a large base_url_v2 and a long model_key
long_base_url_v2 = "x" * 200
long_model_key = "y" * 200
service = LocalUrlService(base_url_v2=long_base_url_v2)
expected_url = f"{long_base_url_v2}/models/i/{long_model_key}/image"
codeflash_output = service.get_model_image_url(long_model_key) # 482ns -> 539ns (10.6% slower)

def test_large_scale_all_ascii_printable_keys():
# Test with all printable ASCII characters as model_key
import string
service = LocalUrlService()
key = string.printable
expected_url = f"api/v2/models/i/{key}/image"
codeflash_output = service.get_model_image_url(key) # 470ns -> 439ns (7.06% faster)

def test_large_scale_varied_base_url_v2():
# Test with many different base_url_v2 values
for i in range(100):
base_url_v2 = f"api/v2/instance_{i}"
service = LocalUrlService(base_url_v2=base_url_v2)
key = f"model_{i}"
expected_url = f"{base_url_v2}/models/i/{key}/image"
codeflash_output = service.get_model_image_url(key) # 19.2μs -> 18.4μs (4.65% faster)

codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

#------------------------------------------------
import random # used for generating large/edge test cases
import string # used for generating large/edge test cases

function to test

from typing import Optional

imports

import pytest # used for our unit tests
from invokeai.app.services.urls.urls_default import LocalUrlService

class UrlServiceBase:
pass # Dummy base class for inheritance
from invokeai.app.services.urls.urls_default import LocalUrlService

unit tests

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

def test_basic_model_key_alpha():
"""Test with a simple alphabetic model_key."""
service = LocalUrlService()
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 472ns -> 461ns (2.39% faster)

def test_basic_model_key_numeric():
"""Test with a numeric model_key."""
service = LocalUrlService()
codeflash_output = service.get_model_image_url("12345"); result = codeflash_output # 484ns -> 464ns (4.31% faster)

def test_basic_model_key_alphanumeric():
"""Test with an alphanumeric model_key."""
service = LocalUrlService()
codeflash_output = service.get_model_image_url("abc123"); result = codeflash_output # 450ns -> 429ns (4.90% faster)

def test_basic_model_key_with_dash_underscore():
"""Test with a model_key containing dashes and underscores."""
service = LocalUrlService()
codeflash_output = service.get_model_image_url("model-01_test"); result = codeflash_output # 483ns -> 473ns (2.11% faster)

def test_basic_custom_base_url_v2():
"""Test with a custom base_url_v2."""
service = LocalUrlService(base_url_v2="custom/v2")
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 501ns -> 497ns (0.805% faster)

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

def test_edge_empty_model_key():
"""Test with an empty string as model_key."""
service = LocalUrlService()
codeflash_output = service.get_model_image_url(""); result = codeflash_output # 501ns -> 469ns (6.82% faster)

def test_edge_model_key_special_characters():
"""Test with special characters in model_key."""
service = LocalUrlService()
special_key = "!@#$%^&*()[]{};:,.<>?|"
codeflash_output = service.get_model_image_url(special_key); result = codeflash_output # 492ns -> 488ns (0.820% faster)

def test_edge_model_key_unicode():
"""Test with unicode characters in model_key."""
service = LocalUrlService()
unicode_key = "模型测试🚀"
codeflash_output = service.get_model_image_url(unicode_key); result = codeflash_output # 853ns -> 848ns (0.590% faster)

def test_edge_model_key_with_slash():
"""Test with a model_key containing slashes."""
service = LocalUrlService()
key_with_slash = "folder/subfolder/model"
codeflash_output = service.get_model_image_url(key_with_slash); result = codeflash_output # 526ns -> 518ns (1.54% faster)

def test_edge_base_url_v2_empty():
"""Test with an empty base_url_v2."""
service = LocalUrlService(base_url_v2="")
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 503ns -> 508ns (0.984% slower)

def test_edge_base_url_v2_special_chars():
"""Test with special characters in base_url_v2."""
service = LocalUrlService(base_url_v2="!@#$/v2")
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 482ns -> 492ns (2.03% slower)

def test_edge_base_url_v2_unicode():
"""Test with unicode in base_url_v2."""
service = LocalUrlService(base_url_v2="测试/v2")
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 787ns -> 595ns (32.3% faster)

def test_edge_model_key_none():
"""Test with None as model_key (should raise TypeError)."""
service = LocalUrlService()
with pytest.raises(TypeError):
# f-string with None will coerce to 'None' string, but let's check for this edge
service.get_model_image_url(None)

def test_edge_model_key_integer():
"""Test with integer as model_key (should raise TypeError)."""
service = LocalUrlService()
with pytest.raises(TypeError):
service.get_model_image_url(123)

def test_edge_model_key_bytes():
"""Test with bytes as model_key (should raise TypeError)."""
service = LocalUrlService()
with pytest.raises(TypeError):
service.get_model_image_url(b"abc")

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

def test_large_model_key_length():
"""Test with a very long model_key (999 characters)."""
service = LocalUrlService()
long_key = "a" * 999
codeflash_output = service.get_model_image_url(long_key); result = codeflash_output # 850ns -> 871ns (2.41% slower)

def test_large_model_key_random():
"""Test with a random model_key of 999 mixed characters."""
service = LocalUrlService()
chars = string.ascii_letters + string.digits + "-_!@#$"
random_key = ''.join(random.choices(chars, k=999))
codeflash_output = service.get_model_image_url(random_key); result = codeflash_output # 719ns -> 728ns (1.24% slower)

def test_large_base_url_v2_length():
"""Test with a very long base_url_v2 (999 characters)."""
long_base = "b" * 999
service = LocalUrlService(base_url_v2=long_base)
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 711ns -> 662ns (7.40% faster)

def test_large_scale_multiple_instances():
"""Test creating many LocalUrlService instances with different base_url_v2 values."""
for i in range(1000):
base_url_v2 = f"api/v2/{i}"
service = LocalUrlService(base_url_v2=base_url_v2)
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 182μs -> 173μs (5.26% faster)

----------- ADDITIONAL EDGE CASES -----------

def test_edge_model_key_leading_trailing_spaces():
"""Test with model_key containing leading/trailing spaces."""
service = LocalUrlService()
key = " abc "
codeflash_output = service.get_model_image_url(key); result = codeflash_output # 553ns -> 505ns (9.50% faster)

def test_edge_base_url_v2_trailing_slash():
"""Test with base_url_v2 ending with a slash."""
service = LocalUrlService(base_url_v2="api/v2/")
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 499ns -> 447ns (11.6% faster)

def test_edge_base_url_v2_leading_slash():
"""Test with base_url_v2 starting with a slash."""
service = LocalUrlService(base_url_v2="/api/v2")
codeflash_output = service.get_model_image_url("abc"); result = codeflash_output # 478ns -> 440ns (8.64% faster)

def test_edge_model_key_only_spaces():
"""Test with model_key that is only spaces."""
service = LocalUrlService()
key = " "
codeflash_output = service.get_model_image_url(key); result = codeflash_output # 536ns -> 448ns (19.6% faster)

def test_edge_model_key_tab_newline():
"""Test with model_key containing tabs and newlines."""
service = LocalUrlService()
key = "\tmodel\n"
codeflash_output = service.get_model_image_url(key); result = codeflash_output # 501ns -> 511ns (1.96% slower)

codeflash_output is used to check that the output of the original code is the same as that of the optimized code.

#------------------------------------------------
from invokeai.app.services.urls.urls_default import LocalUrlService

def test_LocalUrlService_get_model_image_url():
LocalUrlService.get_model_image_url(LocalUrlService(base_url='', base_url_v2=''), '')

🔎 Concolic Coverage Tests and Runtime
Test File::Test Function Original ⏱️ Optimized ⏱️ Speedup
codeflash_concolic_iouvh9ci/tmpqi5gtl_y/test_concolic_coverage.py::test_LocalUrlService_get_model_image_url 520ns 499ns 4.21%✅

To edit these changes git checkout codeflash/optimize-LocalUrlService.get_model_image_url-mhvizjgk and push.

Codeflash Static Badge

The optimization precomputes the static URL prefix `f"{self._base_url_v2}/models/i/"` during initialization and stores it as `self._model_image_url_prefix`. This eliminates redundant string formatting operations in the frequently-called `get_model_image_url` method.

**Key changes:**
- Added `self._model_image_url_prefix = f"{self._base_url_v2}/models/i/"` in `__init__`
- Simplified the return statement to `f"{self._model_image_url_prefix}{model_key}/image"`

**Why it's faster:**
The original code performs two string operations per call: accessing `self._base_url_v2` and formatting the entire URL template. The optimized version reduces this to a single string concatenation by reusing the precomputed prefix. This saves approximately 70ns per call (358.4ns → 287.8ns per hit), resulting in a 5% overall speedup.

**Performance characteristics:**
- **Best gains** (5-32% faster): Empty model keys, whitespace-only keys, unicode base URLs, and scenarios with trailing slashes
- **Consistent improvements** (2-8% faster): Most standard alphanumeric keys and varied base URLs
- **Minimal impact** (0-2% slower): Very long strings and some unicode edge cases where string allocation overhead dominates

This optimization is particularly valuable for URL services that generate many model image URLs, as each call now performs less work with no behavioral changes.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 November 12, 2025 04:54
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Nov 12, 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 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant