Skip to content

Commit 54b3bf1

Browse files
misrasaurabh1codeflash-ai[bot]adhami3310
authored
⚡️ Speed up function to_camel_case by 128% (#5239)
* ⚡️ Speed up function `to_camel_case` by 128% Here's an optimized version of your code. The time-consuming part is the `re.split` operation, used only for splitting on `-` and `_`, which can be replaced with a much faster approach since there are only two possible delimiters. Using `str.replace` is significantly faster for this case, and the generator expression for capitalization is fine, but can be made a tiny bit faster with a list comprehension. All existing comments are preserved. **Optimizations made:** - Removed `re.split`, replacing with a much faster combination of `str.replace` and `str.split`. - Used a list comprehension for joining capitalized words (marginally faster than a generator for `str.join`). - Preserves exact same return values for all inputs and all original comments. This should be much faster, especially for large numbers of short strings. * remove unneeded comment --------- Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com> Co-authored-by: Khaleel Al-Adhami <khaleel.aladhami@gmail.com>
1 parent fd8e12a commit 54b3bf1

1 file changed

Lines changed: 6 additions & 3 deletions

File tree

reflex/utils/format.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,13 @@ def to_camel_case(text: str, treat_hyphens_as_underscores: bool = True) -> str:
181181
Returns:
182182
The camel case string.
183183
"""
184-
char = "_" if not treat_hyphens_as_underscores else "-_"
185-
words = re.split(f"[{char}]", text)
184+
if treat_hyphens_as_underscores:
185+
text = text.replace("-", "_")
186+
words = text.split("_")
186187
# Capitalize the first letter of each word except the first one
187-
converted_word = words[0] + "".join(x.capitalize() for x in words[1:])
188+
if len(words) == 1:
189+
return words[0]
190+
converted_word = words[0] + "".join([w.capitalize() for w in words[1:]])
188191
return converted_word
189192

190193

0 commit comments

Comments
 (0)