Skip to content

Optimize FromUnderscoreDashSeparatedWords to reduce allocations#1660

Open
alexzzzs wants to merge 3 commits intoHumanizr:mainfrom
alexzzzs:perf/optimize-underscore-dash
Open

Optimize FromUnderscoreDashSeparatedWords to reduce allocations#1660
alexzzzs wants to merge 3 commits intoHumanizr:mainfrom
alexzzzs:perf/optimize-underscore-dash

Conversation

@alexzzzs
Copy link

Optimize FromUnderscoreDashSeparatedWords to reduce allocations

Optimizes the FromUnderscoreDashSeparatedWords method to eliminate unnecessary memory allocations.

The original implementation (string.Join(" ", input.Split(['_', '-']))) allocates multiple intermediate strings and arrays for each call.

Changes

  • Replaced string.Join(" ", input.Split(['_', '-'])) with string.Create for .NET 7.0+ (in-place modification)
  • Added Replace fallback for older frameworks
  • Zero temporary allocations, O(N) time complexity

Testing

  • All unit tests pass
  • Builds successful for .NET 8.0, 10.0, and 4.8

@hazzik
Copy link
Collaborator

hazzik commented Jan 7, 2026

@alexzzzs
Copy link
Author

alexzzzs commented Jan 7, 2026

I wrote the manual loop to handle both _ and - in a single pass to avoid iterating over the span twice.
Although, I didn't realise that MemoryExtensions.Replace uses SIMD/vectorization, which would likely make up for that.
I updated the code to use MemoryExtensions.Replace.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR optimizes the FromUnderscoreDashSeparatedWords method to reduce memory allocations during string humanization. The optimization is particularly beneficial when processing strings with underscores or dashes.

Key changes:

  • Replaced string.Join(" ", input.Split(['_', '-'])) with more efficient implementations
  • Added string.Create for .NET 7.0+ to enable zero-allocation in-place character replacement
  • Used chained Replace calls as a fallback for older frameworks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants