Most efficient way to append arrays in C#?

前端 未结 10 2190
挽巷
挽巷 2020-12-02 19:39

I am pulling data out of an old-school ActiveX in the form of arrays of doubles. I don\'t initially know the final number of samples I will actually retrieve.

What i

10条回答
  •  醉话见心
    2020-12-02 20:15

    You might not need to concatenate end result into contiguous array. Instead, keep appending to the list as suggested by Jon. In the end you'll have a jagged array (well, almost rectangular in fact). When you need to access an element by index, use following indexing scheme:

    double x = list[i / sampleSize][i % sampleSize];
    

    Iteration over jagged array is also straightforward:

    for (int iRow = 0; iRow < list.Length; ++iRow) {
      double[] row = list[iRow];
      for (int iCol = 0; iCol < row.Length; ++iCol) {
        double x = row[iCol];
      }
    }
    

    This saves you memory allocation and copying at expense of slightly slower element access. Whether this will be a net performance gain depends on size of your data, data access patterns and memory constraints.

提交回复
热议问题