Search code examples
c#memoryoptimization

Copying a `System.Guid` to `byte[]` without allocating


The application I'm working on is very focused on performance, and as such needs to keep allocations down to a minimum to keep GC stalls down.

I was surprised to find that System.Guid does not expose any method to copy it's byte[] representation into an existing buffer. The only existing method, Guid.ToByteArray(), performs a new byte[] allocation, and otherwise there's no way to get at the underlying bytes without it.

So what I'm looking for is some way to copy a Guid to a an already existing byte[] buffer without allocating any memory (since Guid is a value type already).


Solution

  • The solution I settled on came from some help from the Jil project by Kevin Montrose. I didn't go with that exact solution, but it inspired me to come up with something that I think is fairly elegant.

    Note: The following code uses Fixed Size Buffers and requires that your project be built with the /unsafe switch (and in all likelihood requires Full Trust to run).

    [StructLayout(LayoutKind.Explicit)]
    unsafe struct GuidBuffer
    {
        [FieldOffset(0)]
        fixed long buffer[2];
    
        [FieldOffset(0)]
        public Guid Guid;
    
        public GuidBuffer(Guid guid)
            : this()
        {
            Guid = guid;
        }
    
        public void CopyTo(byte[] dest, int offset)
        {
            if (dest.Length - offset < 16)
                throw new ArgumentException("Destination buffer is too small");
    
            fixed (byte* bDestRoot = dest)
            fixed (long* bSrc = buffer)
            {
                byte* bDestOffset = bDestRoot + offset;
                long* bDest = (long*)bDestOffset;
    
                bDest[0] = bSrc[0];
                bDest[1] = bSrc[1];
            }
        }
    }
    

    Usage is simple:

    var myGuid = Guid.NewGuid(); // however you get it
    var guidBuffer = new GuidBuffer(myGuid);
    
    var buffer = new buffer[16];
    guidBuffer.CopyTo(buffer, 0);
    

    Timing this yielded an average duration of 1-2 ticks for the copy. Should be fast enough for most any application.

    However, if you want to eke out the absolute best performance, one possibility (suggested by Kevin) is to ensure that the offset parameter is long-aligned (on an 8-byte boundary). My particular use case favors memory over speed, but if speed is the most important thing that would be a good way to go about it.