Created
April 6, 2018 16:18
-
-
Save Tornhoof/141f52e2158d0b139590303db86dcfcd to your computer and use it in GitHub Desktop.
DateTime Formatting/Parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Buffers.Text; | |
using System.Globalization; | |
using System.Text; | |
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
namespace FormatterBenchmark | |
{ | |
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
BenchmarkRunner.Run<Benchmark>(); | |
} | |
} | |
[MemoryDiagnoser] | |
public class Benchmark | |
{ | |
private static readonly DateTime DateTimeValue = DateTime.UtcNow; | |
private static readonly char[] DateTimeFormat = {'o'}; | |
private static readonly string s_DtInput = DateTimeValue.ToString("O"); | |
private static readonly byte[] s_DtInputArray = Encoding.UTF8.GetBytes(s_DtInput); | |
private static readonly byte[] s_Buffer = new byte[40]; | |
[Benchmark(Description = "Format DateTime CoreCLR")] | |
public string CoreClrDateTime() | |
{ | |
var dt = DateTimeValue; | |
Span<char> span = stackalloc char[40]; | |
int pos = 0; | |
dt.TryFormat(span, out pos, DateTimeFormat.AsSpan(), CultureInfo.InvariantCulture); | |
return span.Slice(0, pos).ToString(); | |
} | |
[Benchmark(Description = "Format DateTime Utf8Formatter")] | |
public byte[] Utf8FormatterDateTime() | |
{ | |
var dt = DateTimeValue; | |
Span<byte> span = s_Buffer; | |
Utf8Formatter.TryFormat(dt, span, out var written); | |
return s_Buffer; | |
} | |
[Benchmark(Description = "Parse DateTime CoreCLR")] | |
public DateTime ParseCoreClrDateTime() | |
{ | |
var local = s_DtInput; | |
return DateTime.Parse(local.AsSpan(), CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal); | |
} | |
[Benchmark(Description = "Parse DateTime Utf8Formatter")] | |
public DateTime ParseUtf8FormatterDateTime() | |
{ | |
var local = s_DtInputArray; | |
Utf8Parser.TryParse(local.AsSpan(), out DateTime value, out int consumed); | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment