⚡️ Speed up method LocalUrlService.get_model_image_url by 6%
#136
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 6% (0.06x) speedup for
LocalUrlService.get_model_image_urlininvokeai/app/services/urls/urls_default.py⏱️ Runtime :
406 microseconds→385 microseconds(best of193runs)📝 Explanation and details
The optimization precomputes the static URL prefix
f"{self._base_url_v2}/models/i/"during initialization and stores it asself._model_image_url_prefix. This eliminates redundant string formatting operations in the frequently-calledget_model_image_urlmethod.Key changes:
self._model_image_url_prefix = f"{self._base_url_v2}/models/i/"in__init__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_v2and 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:
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:
🌀 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
codeflash_concolic_iouvh9ci/tmpqi5gtl_y/test_concolic_coverage.py::test_LocalUrlService_get_model_image_urlTo edit these changes
git checkout codeflash/optimize-LocalUrlService.get_model_image_url-mhvizjgkand push.