-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Runtime
Milestone
Description
Background and motivation
Since Span type was created a lot of types added TryFormat method to write the value as text into a destination span. In .NET 6 these methods were added for char and bool types, however for enum type I could not find anything. I suggest to add it.
I also would like to submit a PR for this.
My current implementation got good results:
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.18363.1440 (1909/November2019Update/19H2)
Intel Core i7-8650U CPU 1.90GHz (Kaby Lake R), 1 CPU, 8 logical and 4 physical cores
.NET SDK=6.0.100-preview.6.21355.2
[Host] : .NET 6.0.0 (6.0.21.35212), X64 RyuJIT
DefaultJob : .NET 6.0.0 (6.0.21.35212), X64 RyuJIT
| Method | N | Mean | Error | StdDev | Median | Gen 0 | Allocated |
|---|---|---|---|---|---|---|---|
| SPAN_Parse_text | 100000 | 976.3 μs | 36.55 μs | 106.6 μs | 926.1 μs | - | 128 B |
| SPAN_Parse_number | 100000 | 1,949.5 μs | 86.76 μs | 255.8 μs | 1,913.6 μs | - | 128 B |
| STR_Parse_text | 100000 | 2,942.4 μs | 99.17 μs | 290.8 μs | 2,806.8 μs | 570.3125 | 2,400,257 B |
| STR_Parse_number | 100000 | 4,418.8 μs | 139.81 μs | 405.6 μs | 4,231.5 μs | 1335.9375 | 5,600,602 B |
API Proposal
namespace System {
public abstract class Enum : ValueType, IComparable, IConvertible, IFormattable {
// new methods
public static bool TryFormat<TEnum>(TEnum value, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = default)
where TEnum : struct, Enum;
}
}API Usage
Span<char> destination = new char[50];
var isSuccess = Enum.TryFormat(Color.LightBlue, destination, out var charsWritten);
Debug.Assert(isSuccess);
Debug.Assert(destination.Slice(0, charsWritten).SequenceEqual(nameof(Color.LightBlue)));Risks
I dont see any risk
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Runtime