C#C
C#2y ago
substitute

new Span vs stackalloc

I'm working on a library that is able to read and write memory from a remote computer and was wondering which of these two is better practice?

            public void WriteFloat(uint address, float value)
            {
                Span<byte> memory = stackalloc byte [sizeof(float)]
                BinaryPrimitives.WriteSingleBigEndian(memory, value);
                SetMemory(address, memory, out _);
            }


            public void WriteFloat(uint address, float value)
            {
                var memory = MemoryMarshal.Cast<float, byte>(new Span<float>(ref value));
                BinaryPrimitives.WriteSingleBigEndian(memory, value);
                SetMemory(address, memory, out _);
            }


I feel as though these would produce extremely if not exactly the same memory layouts, it creates a Span in both.
Was this page helpful?