Code examples for perf-oriented API suggest inefficient code
- Dominant language
- No language data
- Stars
- 4.8k
- Forks
- 6.1k
- Avg merge
- 15h 21m
- Merged PRs (30d)
- 370
Description
### Type of issue
Other (describe below)
### Description
The first code example under `Utf8Parser and Utf8Formatter` contains this code in the overridden `Write` method:
```
Span utf8Date = new byte[29];
```
Allocating a new byte array every time a `DateTime` value is written seems to be a considerable overhead. Allocating byte array on the stack instead would be more efficient.
Also, that section begins with the statement "if your input DateTime or DateTimeOffset text representations are compliant with one of the "R", "l", "O", or "G" standard date and time format strings". It seems like this is not a limitation and the value can be serialized using any supported format. For example, here's how DateTime value can be written in "s" format:
```
public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
{
Span span = stackalloc char[32];
value.TryFormat(span, out var count, "s");
writer.WriteStringValue(span[..count]);
}
```
### Page URL
https://learn.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support#-and-
### Content source URL
https://github.com/dotnet/docs/blob/main/docs/standard/datetime/system-text-json-support.md
### Document Version Independent Id
77358796-3ee2-9b86-7e0a-92c60ebc371a
### Platform Id
45e1d7c2-9630-1091-5921-5194b2bfef72
### Article author
@layomia
### Metadata
* ID: eb41b02f-8fe9-44a1-544f-b6016f1ff4b3
* PlatformId: 45e1d7c2-9630-1091-5921-5194b2bfef72
* Service: **dotnet-fundamentals**
[Related Issues](https://github.com/dotnet/docs/issues?q=is%3Aissue+is%3Aopen+77358796-3ee2-9b86-7e0a-92c60ebc371a)
Contributor guide
Assessment
This issue has not been assessed yet.