Skip to content

Commit

Permalink
Made Append(bool) faster
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Nov 8, 2024
1 parent 62dc8df commit 9442bdf
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ All notable changes to **ValueStringBuilder** will be documented in this file. T

## [Unreleased]

### Changed
- `Append(bool)` is now 33% faster

## [1.21.0] - 2024-09-20

### Added
Expand Down
32 changes: 24 additions & 8 deletions src/LinkDotNet.StringBuilder/ValueStringBuilder.Append.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,38 @@ public ref partial struct ValueStringBuilder
/// </summary>
/// <param name="value">Bool value to add.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(bool value)
public unsafe void Append(bool value)
{
// 5 is the length of the string "False"
// So we can check if we have enough space in the buffer
var newSize = bufferPosition + 5;
const int trueLength = 4;
const int falseLength = 5;

var newSize = bufferPosition + falseLength;

if (newSize > buffer.Length)
{
Grow(newSize);
}

if (!value.TryFormat(buffer[bufferPosition..], out var charsWritten))
fixed (char* dest = &buffer[bufferPosition])
{
throw new InvalidOperationException($"Could not add {value} to the builder.");
if (value)
{
*(dest + 0) = 'T';
*(dest + 1) = 'r';
*(dest + 2) = 'u';
*(dest + 3) = 'e';
bufferPosition += trueLength;
}
else
{
*(dest + 0) = 'F';
*(dest + 1) = 'a';
*(dest + 2) = 'l';
*(dest + 3) = 's';
*(dest + 4) = 'e';
bufferPosition += falseLength;
}
}

bufferPosition += charsWritten;
}

/// <summary>
Expand Down

0 comments on commit 9442bdf

Please sign in to comment.