Copy array to struct array as fast as possible in C#

前端 未结 5 1875
逝去的感伤
逝去的感伤 2020-12-16 21:24

I am working with Unity 4.5, grabbing images as bytes arrays (each byte represent a channel, taking 4 bytes per pixel (rgba) and displaying them on a texture converting the

5条回答
  •  盖世英雄少女心
    2020-12-16 22:13

    I haven't profiled it, but using fixed to ensure your memory doesn't get moved around and to remove bounds checks on array accesses might provide some benefit:

    img = new Color32[byteArray.Length / nChannels]; //nChannels being 4
    fixed (byte* ba = byteArray)
    {
        fixed (Color32* c = img)
        {
            byte* byteArrayPtr = ba;
            Color32* colorPtr = c;
            for (int i = 0; i < img.Length; i++)
            {
                (*colorPtr).r = *byteArrayPtr++;
                (*colorPtr).g = *byteArrayPtr++;
                (*colorPtr).b = *byteArrayPtr++;
                (*colorPtr).a = *byteArrayPtr++;
                colorPtr++;
            }
        }
    }
    

    It might not provide much more benefit on 64-bit systems - I believe that the bounds checking is is more highly optimized. Also, this is an unsafe operation, so take care.

提交回复
热议问题