Skip to content

⚡️ Speed up function word_frequency by 19.87%#313

Open
codeflash-ai[bot] wants to merge 1 commit intomainfrom
codeflash/optimize-word_frequency-mnhpimr9
Open

⚡️ Speed up function word_frequency by 19.87%#313
codeflash-ai[bot] wants to merge 1 commit intomainfrom
codeflash/optimize-word_frequency-mnhpimr9

Conversation

@codeflash-ai
Copy link
Copy Markdown

@codeflash-ai codeflash-ai bot commented Apr 2, 2026

📄 19.87% (0.20x) speedup for word_frequency in src/algorithms/string.py

⏱️ Runtime : 4.21 milliseconds 3.51 milliseconds (best of 213 runs)

📝 Explanation and details

The word_frequency function replaced an if-else branch (if word in frequency: frequency[word] += 1 else: frequency[word] = 1) with a single assignment using dict.get(word, 0) + 1, eliminating a redundant dictionary lookup on every word occurrence. Each lookup in the original code checked membership then accessed the key again for increment, whereas get performs one hash lookup and returns a default if missing, reducing per-word overhead and yielding a 19% runtime improvement with no trade-offs.

Correctness verification report:

Test Status
📊 Tests Coverage Coverage: 100.0% for word_frequency

To edit these changes git checkout codeflash/optimize-word_frequency-mnhpimr9 and push.

Codeflash Static Badge

The `word_frequency` function replaced an if-else branch (`if word in frequency: frequency[word] += 1 else: frequency[word] = 1`) with a single assignment using `dict.get(word, 0) + 1`, eliminating a redundant dictionary lookup on every word occurrence. Each lookup in the original code checked membership then accessed the key again for increment, whereas `get` performs one hash lookup and returns a default if missing, reducing per-word overhead and yielding a 19% runtime improvement with no trade-offs.
@codeflash-ai codeflash-ai bot requested a review from KRRT7 April 2, 2026 16:46
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: Medium Optimization Quality according to Codeflash labels Apr 2, 2026
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: Medium Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants