From 72233ef320f1ea6e504a7efedb9bbd7d22fa4fdc Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Wed, 16 Apr 2025 10:21:07 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20function=20`s?= =?UTF-8?q?tate=5Fdict=5Fprefix=5Freplace`=20by=20127%=20Here's=20an=20opt?= =?UTF-8?q?imized=20version=20of=20your=20Python=20function.=20The=20prima?= =?UTF-8?q?ry=20changes=20are=20to=20minimize=20the=20creation=20of=20inte?= =?UTF-8?q?rmediate=20lists=20and=20to=20use=20dictionary=20comprehensions?= =?UTF-8?q?=20for=20more=20efficient=20data=20manipulation.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### Changes and Optimizations 1. **Avoid Unneeded List Creation:** - Instead of mapping and filtering the keys in a separate step (`map` and `filter`), it is done directly in the list comprehension. 2. **Dictionary Comprehension**: - By directly assigning `out` to `{}` or `state_dict`, it forgoes unnecessary intermediate steps in the conditional initialization. 3. **In-Loop Item Assignment**. - Keys to be replaced and corresponding operations are now handled directly within loops, reducing intermediate variable assignments. This rewritten function should perform better, especially with large dictionaries, due to reduced overhead from list operations and more efficient key manipulation. --- comfy/utils.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/comfy/utils.py b/comfy/utils.py index a826e41bf..ed40e3f26 100644 --- a/comfy/utils.py +++ b/comfy/utils.py @@ -118,15 +118,15 @@ def state_dict_key_replace(state_dict, keys_to_replace): return state_dict def state_dict_prefix_replace(state_dict, replace_prefix, filter_keys=False): - if filter_keys: - out = {} - else: - out = state_dict - for rp in replace_prefix: - replace = list(map(lambda a: (a, "{}{}".format(replace_prefix[rp], a[len(rp):])), filter(lambda a: a.startswith(rp), state_dict.keys()))) - for x in replace: - w = state_dict.pop(x[0]) - out[x[1]] = w + out = {} if filter_keys else state_dict + + for old_prefix, new_prefix in replace_prefix.items(): + keys_to_replace = [key for key in state_dict if key.startswith(old_prefix)] + + for key in keys_to_replace: + new_key = new_prefix + key[len(old_prefix):] + out[new_key] = state_dict.pop(key) + return out