-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuiderBenchmarks.cs
More file actions
102 lines (85 loc) · 2.75 KB
/
GuiderBenchmarks.cs
File metadata and controls
102 lines (85 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using BenchmarkDotNet.Attributes;
using System.Buffers.Text;
using System.Runtime.InteropServices;
namespace GuidBenchmark
{
[MemoryDiagnoser]
public class GuiderBenchmarks
{
private static readonly Guid TestGuidId = Guid.Parse("25fa07b1-cebd-4c78-b23a-a17b3f4845ce");
private const string TestIdAsString = "sQf6Jb3OeEyyOqF7P0hFzg";
[Benchmark]
public Guid ToGuidFromString()
{
return Guider.ToGuidFromString(TestIdAsString);
}
[Benchmark]
public Guid ToGuidFromString_Span()
{
return Guider.ToGuidFromStringOp(TestIdAsString);
}
[Benchmark]
public string ToStingFromGuid()
{
return Guider.ToStringFromGuid(TestGuidId);
}
[Benchmark]
public string ToStingFromGuid_Span()
{
return Guider.ToStringFromGuidOp(TestGuidId);
}
}
public static class Guider
{
public static string ToStringFromGuid(Guid id)
{
return Convert.ToBase64String(id.ToByteArray())
.Replace("/", "-")
.Replace("+", "_")
.Replace("=", string.Empty);
}
public static Guid ToGuidFromString(string id)
{
byte[] efficientBase64 = Convert.FromBase64String(id
.Replace("-", "/")
.Replace("_", "+") + "==");
return new Guid(efficientBase64);
}
public static Guid ToGuidFromStringOp(string id)
{
Span<char> base64Chars = stackalloc char[24];
for (int i = 0; i < 22; i++)
{
base64Chars[i] = id[i] switch
{
'/' => '-',
'_' => '+',
_ => id[i]
};
}
base64Chars[22] = '=';
base64Chars[23] = '=';
Span<byte> idBytes = stackalloc byte[16];
Convert.TryFromBase64Chars(base64Chars, idBytes, out _);
return new Guid(idBytes);
}
public static string ToStringFromGuidOp(Guid id)
{
Span<byte> idBytes = stackalloc byte[16];
Span<byte> base64Bytes = stackalloc byte[24];
MemoryMarshal.TryWrite(idBytes, ref id);
Base64.EncodeToUtf8(idBytes, base64Bytes, out _, out _);
Span<char> finalChars = stackalloc char[22];
for (int i = 0; i < 22; i++)
{
finalChars[i] = base64Bytes[i] switch
{
(byte) '/' => '-',
(byte) '+' => '_',
_ => (char) base64Bytes[i]
};
}
return new string(finalChars);
}
}
}