Skip to content

Commit 9442bdf

Browse files
committed
Made Append(bool) faster
1 parent 62dc8df commit 9442bdf

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

CHANGELOG.md

+3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ All notable changes to **ValueStringBuilder** will be documented in this file. T
66

77
## [Unreleased]
88

9+
### Changed
10+
- `Append(bool)` is now 33% faster
11+
912
## [1.21.0] - 2024-09-20
1013

1114
### Added

src/LinkDotNet.StringBuilder/ValueStringBuilder.Append.cs

+24-8
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,38 @@ public ref partial struct ValueStringBuilder
1010
/// </summary>
1111
/// <param name="value">Bool value to add.</param>
1212
[MethodImpl(MethodImplOptions.AggressiveInlining)]
13-
public void Append(bool value)
13+
public unsafe void Append(bool value)
1414
{
15-
// 5 is the length of the string "False"
16-
// So we can check if we have enough space in the buffer
17-
var newSize = bufferPosition + 5;
15+
const int trueLength = 4;
16+
const int falseLength = 5;
17+
18+
var newSize = bufferPosition + falseLength;
19+
1820
if (newSize > buffer.Length)
1921
{
2022
Grow(newSize);
2123
}
2224

23-
if (!value.TryFormat(buffer[bufferPosition..], out var charsWritten))
25+
fixed (char* dest = &buffer[bufferPosition])
2426
{
25-
throw new InvalidOperationException($"Could not add {value} to the builder.");
27+
if (value)
28+
{
29+
*(dest + 0) = 'T';
30+
*(dest + 1) = 'r';
31+
*(dest + 2) = 'u';
32+
*(dest + 3) = 'e';
33+
bufferPosition += trueLength;
34+
}
35+
else
36+
{
37+
*(dest + 0) = 'F';
38+
*(dest + 1) = 'a';
39+
*(dest + 2) = 'l';
40+
*(dest + 3) = 's';
41+
*(dest + 4) = 'e';
42+
bufferPosition += falseLength;
43+
}
2644
}
27-
28-
bufferPosition += charsWritten;
2945
}
3046

3147
/// <summary>

0 commit comments

Comments
 (0)