Skip to content
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

Migrate Utf8Formatter to Span<T>.Fill #52591

Closed
wants to merge 2 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,6 @@ public static char GetSymbolOrDefault(in StandardFormat format, char defaultSymb

#region UTF-8 Helper methods

/// <summary>
/// Fills a buffer with the ASCII character '0' (0x30).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FillWithAsciiZeros(Span<byte> buffer)
{
// This is a faster implementation of Span<T>.Fill().
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)'0';
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteDigits(ulong value, Span<byte> buffer)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ private static bool TryFormatUInt64D(ulong value, byte precision, Span<byte> des

if (leadingZeroCount > 0)
{
FormattingHelpers.FillWithAsciiZeros(destination.Slice(0, leadingZeroCount));
// Fill with ASCII zeros
destination.Slice(0, leadingZeroCount).Fill((byte)'0');
Copy link
Member

Choose a reason for hiding this comment

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

Note that Utf8Formatter is typically going to use this method for very small sizes. Is Array.Fill faster for these small sizes?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I run some tests, it seems the for loop may be faster for leadingZeroCount < 8.

}
FormattingHelpers.WriteDigits(value, destination.Slice(leadingZeroCount, digitCount));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ private static bool TryFormatUInt64N(ulong value, byte precision, Span<byte> des
if (trailingZeroCount > 0)
{
destination[digitCount + commaCount] = Utf8Constants.Period;
FormattingHelpers.FillWithAsciiZeros(destination.Slice(digitCount + commaCount + 1, trailingZeroCount));

// Fill with ASCII zeros
destination.Slice(digitCount + commaCount + 1, trailingZeroCount).Fill((byte)'0');
}

return true;
Expand Down