From 96f62be75bc6d83aefe20bf91dac53bb0b769bf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joonatan=20Uusv=C3=A4li?= Date: Tue, 3 Nov 2026 13:50:59 +0200 Subject: [PATCH 1/2] Co-locate the generation lock and the last ULID on one cache line The lock and the last generated ULID are always used together inside the critical section, so keeping them on separate cache lines made every lock hand-off between cores move two lines. They now share one line, while the leading and trailing padding in `Ulid.New.GenerationOptions.cs` still keeps neighboring heap objects off it. With one shared `GenerationOptions` instance, throughput on 2-16 threads is mostly 1.4-3.4x higher; single-threaded use and per-thread instances are unchanged. --- src/Ulid/Ulid.New.GenerationOptions.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Ulid/Ulid.New.GenerationOptions.cs b/src/Ulid/Ulid.New.GenerationOptions.cs index c922c5c..7a1007f 100644 --- a/src/Ulid/Ulid.New.GenerationOptions.cs +++ b/src/Ulid/Ulid.New.GenerationOptions.cs @@ -186,9 +186,9 @@ protected GenerationOptions(GenerationOptions original) CurrentState = new(); } - // Separates Lock and LastUlid into different cache lines to prevent "false sharing" - // x64 has 64-byte cache lines; ARM64 (e.g., Apple Silicon) has 128-byte cache lines - // The leading and trailing padding keep neighboring heap objects off those cache lines. + // Keeps the lock and the last ULID on one cache line, as they are always used together, while the leading + // and trailing padding keep neighboring heap objects off that cache line to prevent "false sharing". + // x64 has 64-byte cache lines; ARM64 (e.g., Apple Silicon) has 128-byte cache lines. [StructLayout(LayoutKind.Explicit)] internal class State { @@ -198,11 +198,11 @@ internal class State // The last generated ULID as two numeric (not byte order) halves, so that increments need no byte swaps #pragma warning disable CS0649 // Field is never assigned to, and will always have its default value - [FieldOffset(_cacheLineSize * 2)] public ulong LastUlidPart0; - [FieldOffset(_cacheLineSize * 2 + 8)] public ulong LastUlidPart1; + [FieldOffset(_cacheLineSize + 8)] public ulong LastUlidPart0; + [FieldOffset(_cacheLineSize + 16)] public ulong LastUlidPart1; #pragma warning disable CS0169 // Padding field is never used - [FieldOffset(_cacheLineSize * 3 + 8)] private readonly ulong _trailingPadding; + [FieldOffset(_cacheLineSize * 2 + 16)] private readonly ulong _trailingPadding; #pragma warning restore CS0169 #pragma warning restore CS0649 // Field is never assigned to, and will always have its default value From 8a461f0c7838cb38eb5733441c44412255043a8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joonatan=20Uusv=C3=A4li?= Date: Tue, 3 Nov 2026 13:50:59 +0200 Subject: [PATCH 2/2] Speed up GUID conversion on .NET 7-9 and in the scalar fallback `Vector128.Shuffle` is only a single instruction from .NET 10 on, so `ToGuid` and `New(Guid)` took 12-15 ns on .NET 7-9. Those targets now use the SSSE3 shuffle like `net5.0` and `net6.0`, bringing them to about 0.5 ns. The scalar fallback now writes a ULID result with one 8-byte store instead of two 4-byte stores read back as one load, which brings `New(Guid)` from 5.2 ns to 0.9 ns. A new test pins the byte mapping with a known GUID. Arm CPUs on .NET 7-9 now use the scalar fallback, which was not measured. --- src/Ulid.Tests/Ulid.Guid.Tests.cs | 39 +++++++++++++++++++++++++++++++ src/Ulid/Ulid.Guid.cs | 20 ++++++++++++---- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/src/Ulid.Tests/Ulid.Guid.Tests.cs b/src/Ulid.Tests/Ulid.Guid.Tests.cs index f7587ae..a12c297 100644 --- a/src/Ulid.Tests/Ulid.Guid.Tests.cs +++ b/src/Ulid.Tests/Ulid.Guid.Tests.cs @@ -17,6 +17,45 @@ public void FromAndToGuid_ShouldPreserveValue() Assert.Equal(ulid, ulidFromGuid); // Ensure the ULID matches after conversion } + [Fact] + public void ToGuid_ShouldKeepTheByteOrderOfTheStringRepresentation() + { + // Arrange + // The canonical text of a GUID lists its bytes in the same order as the bytes of a ULID, + // whereas the in-memory layout of a Guid stores its first three fields in little-endian order. + byte[] ulidBytes = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]; + var expected = new Guid("00112233-4455-6677-8899-aabbccddeeff"); + var ulid = Ulid.New(ulidBytes); + + // Act & Assert + Assert.Equal(expected, ulid.ToGuid()); + Assert.Equal(expected, (Guid)ulid); + Assert.Equal(ulid, Ulid.New(expected)); + Assert.Equal(ulidBytes, Ulid.New(expected).ToByteArray()); + } + + [Fact] + public void FromAndToGuid_RandomValues_ShouldMatchTheGuidByteOrder() + { + // Arrange + var random = new Random(4711); + var bytes = new byte[16]; + + for (var i = 0; i < 10_000; i++) + { + random.NextBytes(bytes); + + // Act + var ulid = Ulid.New(bytes); + var guid = ulid.ToGuid(); + + // Assert + Assert.Equal(ulid.ToString(), Ulid.New(guid).ToString()); + Assert.Equal(guid.ToString("N"), Convert.ToHexString(bytes).ToLowerInvariant()); + Assert.Equal(ulid, Ulid.New(guid)); + } + } + [Fact] public void FromAndToGuid_ImplicitConversion_ShouldPreserveValue() { diff --git a/src/Ulid/Ulid.Guid.cs b/src/Ulid/Ulid.Guid.cs index 667b56c..735189b 100644 --- a/src/Ulid/Ulid.Guid.cs +++ b/src/Ulid/Ulid.Guid.cs @@ -2,7 +2,7 @@ using System.Runtime.CompilerServices; #if NETCOREAPP using System.Runtime.Intrinsics; -#if !NET7_0_OR_GREATER +#if !NET10_0_OR_GREATER using System.Runtime.Intrinsics.X86; #endif #endif @@ -63,7 +63,7 @@ private static Vector128 _shuffleMask [MethodImpl(MethodImplOptions.AggressiveInlining)] private static TOut Shuffle(ref TIn bytes) { -#if NET7_0_OR_GREATER +#if NET10_0_OR_GREATER if (Vector128.IsHardwareAccelerated) { var vector = Unsafe.As>(ref bytes); @@ -71,6 +71,7 @@ private static TOut Shuffle(ref TIn bytes) return Unsafe.As, TOut>(ref vector); } #elif NETCOREAPP3_0_OR_GREATER + // Vector128.Shuffle is not expanded to a single instruction before .NET 10 if (Ssse3.IsSupported) { var vector = Unsafe.As>(ref bytes); @@ -93,8 +94,19 @@ private static TOut Shuffle(ref TIn bytes) Unsafe.SkipInit(out TOut result); ref var dst = ref Unsafe.As(ref result); - Unsafe.WriteUnaligned(ref dst, lower); - Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, 4), upper); + if (typeof(TOut) == typeof(Ulid)) + { + // A Ulid is read back as a whole. When its first 8 bytes are written in smaller pieces, the CPU cannot + // forward the stores to that wider load and stalls. The shuffle only runs on little-endian systems. + Unsafe.WriteUnaligned(ref dst, lower | ((ulong)upper << 32)); + } + else + { + // A Guid is made of separate fields, which are written and read back one by one + Unsafe.WriteUnaligned(ref dst, lower); + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, 4), upper); + } + Unsafe.WriteUnaligned(ref Unsafe.Add(ref dst, 8), Unsafe.ReadUnaligned(ref Unsafe.Add(ref src, 8))); return result;