Skip to content

Commit

Permalink
Make SequentialGuidValueGenerator non-allocating (dotnet#30649)
Browse files Browse the repository at this point in the history
Co-authored-by: Shay Rojansky <roji@roji.org>
  • Loading branch information
NKnusperer and roji authored Apr 16, 2023
1 parent 65bb6b0 commit 0386a9b
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/EFCore/ValueGeneration/SequentialGuidValueGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Runtime.InteropServices;

namespace Microsoft.EntityFrameworkCore.ValueGeneration;

/// <summary>
Expand Down Expand Up @@ -33,12 +35,16 @@ public class SequentialGuidValueGenerator : ValueGenerator<Guid>
/// <returns>The value to be assigned to a property.</returns>
public override Guid Next(EntityEntry entry)
{
var guidBytes = Guid.NewGuid().ToByteArray();
var counterBytes = BitConverter.GetBytes(Interlocked.Increment(ref _counter));
Span<byte> guidBytes = stackalloc byte[16];
var succeeded = Guid.NewGuid().TryWriteBytes(guidBytes);
Check.DebugAssert(succeeded, "Could not write Guid to Span");
var incrementedCounter = Interlocked.Increment(ref _counter);
Span<byte> counterBytes = stackalloc byte[sizeof(long)];
MemoryMarshal.Write(counterBytes, ref incrementedCounter);

if (!BitConverter.IsLittleEndian)
{
Array.Reverse(counterBytes);
counterBytes.Reverse();
}

guidBytes[08] = counterBytes[1];
Expand Down

0 comments on commit 0386a9b

Please sign in to comment.