Skip to content

Commit 2efb63a

Browse files
committed
C# guid optimizations with stackalloc and Span<byte>
1 parent 3f2d5ef commit 2efb63a

File tree

3 files changed

+15
-9
lines changed

3 files changed

+15
-9
lines changed

projects/CSharp/Proto/com.chronoxor.fbe.cs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,17 +76,20 @@ public static Guid Sequential()
7676
}
7777

7878
long ticks = (now - GregorianEpoch).Ticks;
79-
byte[] guid = new byte[16];
79+
Span<byte> guid = stackalloc byte[16];
8080
byte[] timestamp = BitConverter.GetBytes(ticks);
8181

8282
// Copy node
83-
Array.Copy(NodeBytes, 0, guid, 10, Math.Min(6, NodeBytes.Length));
83+
for (int i = 0; i < Math.Min(6, NodeBytes.Length); i++)
84+
guid[10 + i] = NodeBytes[i];
8485

8586
// Copy clock sequence
86-
Array.Copy(ClockSequenceBytes, 0, guid, 8, Math.Min(2, ClockSequenceBytes.Length));
87+
for (int i = 0; i < Math.Min(2, ClockSequenceBytes.Length); i++)
88+
guid[8 + i] = ClockSequenceBytes[i];
8789

8890
// Copy timestamp
89-
Array.Copy(timestamp, 0, guid, 0, Math.Min(8, timestamp.Length));
91+
for (int i = 0; i < Math.Min(8, timestamp.Length); i++)
92+
guid[i] = timestamp[i];
9093

9194
// Set the variant
9295
guid[8] &= 0x3F;

projects/CSharp/Tests/Tests.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
</PropertyGroup>
66
<ItemGroup>
77
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
8-
<PackageReference Include="xunit" Version="2.4.1" />
8+
<PackageReference Include="xunit" Version="2.4.2" />
99
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
1010
<PrivateAssets>all</PrivateAssets>
1111
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

source/generator_csharp.cpp

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -133,17 +133,20 @@ void GeneratorCSharp::GenerateFBEUuidGenerator()
133133
}
134134
135135
long ticks = (now - GregorianEpoch).Ticks;
136-
byte[] guid = new byte[16];
136+
Span<byte> guid = stackalloc byte[16];
137137
byte[] timestamp = BitConverter.GetBytes(ticks);
138138
139139
// Copy node
140-
Array.Copy(NodeBytes, 0, guid, 10, Math.Min(6, NodeBytes.Length));
140+
for (int i = 0; i < Math.Min(6, NodeBytes.Length); i++)
141+
guid[10 + i] = NodeBytes[i];
141142
142143
// Copy clock sequence
143-
Array.Copy(ClockSequenceBytes, 0, guid, 8, Math.Min(2, ClockSequenceBytes.Length));
144+
for (int i = 0; i < Math.Min(2, ClockSequenceBytes.Length); i++)
145+
guid[8 + i] = ClockSequenceBytes[i];
144146
145147
// Copy timestamp
146-
Array.Copy(timestamp, 0, guid, 0, Math.Min(8, timestamp.Length));
148+
for (int i = 0; i < Math.Min(8, timestamp.Length); i++)
149+
guid[i] = timestamp[i];
147150
148151
// Set the variant
149152
guid[8] &= 0x3F;

0 commit comments

Comments
 (0)