简体   繁体   中英

Fast creation of 2D array from 1D array of objects

I need to convert the following 1D array of my class Frames to a 2D byte array (I need the 2D byte array for sending to a GPU, I cannot use jagged arrays, Lists, or other enumerables).

Right now, my conversion is very slow and stupid:

public byte[,] allBytes()
{
    byte[,] output = new byte[this.frameListSize, this.ySize * this.xSize];
    for (int y = 0; y < this.frameListSize; y++)
    {
        byte[] bits = this.frameList[y].getBytes();
        for (int x = 0; x < this.ySize * this.xSize; x++)
        {
            output[y, x] = bits[x];
        }
    }
    return output;
}

The snippets that define of frameList and Frame are below:

public Frame[] frameList;

public class Frame
{

  public byte[] bits;

  public byte[] getBytes()
  {
    return bits;
  }
}

If you use .NET Framework 4 or higher, you can use Parallel (for a first speeding up)

    public byte[,] allBytes()
    {
        int size1 = this.frameListSize;
        int size2 = this.ySize * this.xSize;
        byte[,] output = new byte[size1, size2];
        Parallel.For(0, size1, (y) =>
        {
            byte[] bits = this.frameList[y].getBytes();
            System.Buffer.BlockCopy(bits, 0, output, 0 + size2 * y, bits.Length);
        });
        return output;
    }

Buffer.BlockCopy is about 20 times faster than normal copying. Make sure bits.Length has the same value as size2. Otherwise you can run into errors

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM