1

I'm writing custom byte stream and I want the most the write/read methods that works the fastest way possible. This is my current implementation of the write and read methods for int32:

    public void write(int value)
    {
        unchecked
        {
            bytes[index++] = (byte)(value);
            bytes[index++] = (byte)(value >> 8);
            bytes[index++] = (byte)(value >> 16);
            bytes[index++] = (byte)(value >> 24);
        }
    }

    public int readInt()
    {
        unchecked
        {
            return bytes[index++] |
                (bytes[index++] << 8) |
                (bytes[index++] << 16) |
                (bytes[index++] << 24);
        }
    }

But what I really want is to do is cast the "int" into a byte pointer (or something like that) and copy the memory into the "bytes" array with the given "index" as the offset. Is it even possible in C#?

The goal is to:
Avoid creating new arrays.
Avoid loops.
Avoid multiple assignment of the "index" variable.
Reduce the number of instructions.

William S.
  • 21
  • 4
  • note that MSFT BinaryWriter does it how you do it in yr question. http://referencesource.microsoft.com/#mscorlib/system/io/binarywriter.cs,279 – pm100 Sep 05 '17 at 21:49
  • have a look at the various answer of _float[] to byte[]_ https://stackoverflow.com/questions/619041 – devio Sep 05 '17 at 22:03
  • Have you looked at BitConverter? Also, do you care about endianness? – Dave M Sep 06 '17 at 00:21

2 Answers2

1

Your code is very fast, but you can speed it even more (almost 2x faster) with the following change:

bytes[index] = (byte)(value);
bytes[index+1] = (byte)(value >> 8);
bytes[index+2] = (byte)(value >> 16);
bytes[index+3] = (byte)(value >> 24);
index = index + 4;
Sach
  • 10,091
  • 8
  • 47
  • 84
David Kujawski
  • 319
  • 1
  • 7
1
unsafe
{
    fixed (byte* pbytes = &bytes[index])
    {
        *(int*)pbytes = value;
        value = *(int*)pbytes;
    }
}

But be careful with possible array index overflow.

ryanovic
  • 114
  • 1
  • 4
  • Exactly what I was looking for. I did mess a bit with unsafe scope, but didn't really know much about it. The fixed keyword only "tags" the memory so it can't be moved? Or is it copied to a safe place? – William S. Sep 06 '17 at 01:35
  • Another thing, does C# guarantees the endianness on every machine? – William S. Sep 06 '17 at 01:37
  • Yep, it just prevents array from to be moved during garbage collection - doesn't copy anywhere. Endianness depends on target platform architecture - see [BitConverter.IsLittleEndian](https://msdn.microsoft.com/en-us/library/system.bitconverter.islittleendian(v=vs.110).aspx) – ryanovic Sep 06 '17 at 10:33
  • 1
    Doesn't fixed keyword have a performance cost? E.g. cost of pinning the pointer? – JBeurer Feb 16 '18 at 14:30
  • 1
    better solution in safe context: Unsafe.As(ref bytes[index]) = value; – Vein Jun 04 '19 at 16:14