⚡️ Speed up function toTitleCase by 13%
#1087
Open
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.
📄 13% (0.13x) speedup for
toTitleCaseincode_to_optimize_js/string_utils.js⏱️ Runtime :
468 microseconds→412 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 13% speedup by eliminating multiple intermediate array allocations and reducing function call overhead.
Key optimizations:
Single-pass character iteration: Instead of
split()→map()→join()which creates multiple intermediate arrays, the optimized version processes each character once in a loop, building the result string directly.Eliminates array overhead: The original approach:
toLowerCase()on entire string (allocation setup github actions #1)split(' ')(allocation Refactor optimizer into FunctionOptimizer class #2)map()with per-wordcharAt()+slice()+toUpperCase()operations (allocation compare stdout #3 + N word allocations)The optimized version only allocates the final result string.
Reduces function calls: Eliminates array method overhead (
split,map,join) and per-word string methods (charAt,slice). Instead uses simple character-by-character conditionals.State-based capitalization: The
capitalizeNextflag efficiently tracks when to capitalize without needing to identify word boundaries upfront.Performance characteristics by test type:
The optimization is particularly effective for typical use cases involving multiple words, which aligns with the common usage patterns shown in the test suite where most tests involve 2-500 words separated by spaces.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-toTitleCase-mkh64r8zand push.