Skip to content

Optimize & simplify Replace(char, char) #241

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ All notable changes to **ValueStringBuilder** will be documented in this file. T

## [Unreleased]

### Changed

- Optimized `Replace(char, char)` (by @Joy-less in #241)
- Optimized `Replace(ReadOnlySpan<char>, ReadOnlySpan<char>)` when both spans are length 1 (by @Joy-less in #241)

## [2.4.0] - 2025-02-21

### Added
Expand Down
14 changes: 7 additions & 7 deletions src/LinkDotNet.StringBuilder/ValueStringBuilder.Replace.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,7 @@ public readonly void Replace(char oldValue, char newValue, int startIndex, int c
ArgumentOutOfRangeException.ThrowIfLessThan(startIndex, 0);
ArgumentOutOfRangeException.ThrowIfGreaterThan(startIndex + count, Length);

for (var i = startIndex; i < startIndex + count; i++)
{
if (buffer[i] == oldValue)
{
buffer[i] = newValue;
}
}
buffer.Slice(startIndex, count).Replace(oldValue, newValue);
}

/// <summary>
Expand Down Expand Up @@ -97,6 +91,12 @@ public void Replace(scoped ReadOnlySpan<char> oldValue, scoped ReadOnlySpan<char
return;
}

if (oldValue.Length == 1 && newValue.Length == 1)
{
Replace(oldValue[0], newValue[0], startIndex, count);
return;
}

var index = startIndex;
var remainingChars = count;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static ValueStringBuilder ToValueStringBuilder(this System.Text.StringBui
{
ArgumentNullException.ThrowIfNull(builder);

var valueStringBuilder = new ValueStringBuilder();
var valueStringBuilder = new ValueStringBuilder(builder.Length);
foreach (var chunk in builder.GetChunks())
{
valueStringBuilder.Append(chunk.Span);
Expand Down