提供的代码片段在将三个数组复制到单个三维数组时表现出缓慢的性能。以下是一些实现更快执行速度的替代解决方案:
Buffer.BlockCopy 专为高速操作数组中的基本类型而设计。与 System.Array 中的类似方法相比,它提供了显着的性能改进。要使用 Buffer.BlockCopy,请按照以下步骤操作:
double[] sortedIndex, sortedInstances, sortedLabels; double[,] leftnode = new double[sortedIndex.Length, 3]; // Copy sortedIndex into the first column of leftnode Buffer.BlockCopy(sortedIndex, 0, leftnode, 0, sortedIndex.Length * sizeof(double)); // Copy sortedInstances into the second column of leftnode Buffer.BlockCopy(sortedInstances, 0, leftnode, sortedIndex.Length * sizeof(double), sortedInstances.Length * sizeof(double)); // Copy sortedLabels into the third column of leftnode Buffer.BlockCopy(sortedLabels, 0, leftnode, sortedIndex.Length * sizeof(double) + sortedInstances.Length * sizeof(double), sortedLabels.Length * sizeof(double));
为了获得最佳性能,您可以直接调用底层函数 System.Buffer.memcpyimpl由 Buffer.BlockCopy 使用。此方法需要指针,但针对最大速度进行了优化。但请注意,它仅对原始数组进行操作。
//assuming arrays of primitives and pointers are available double[] sortedIndex, sortedInstances, sortedLabels; double[,] leftnode = new double[sortedIndex.Length, 3]; unsafe { fixed (double* pSortedIndex = &sortedIndex[0]) fixed (double* pSortedInstances = &sortedInstances[0]) fixed (double* pSortedLabels = &sortedLabels[0]) fixed (double* pLeftnode = &leftnode[0, 0]) { Buffer.memcpyimpl((byte*)pSortedIndex, (byte*)pLeftnode, sortedIndex.Length * sizeof(double)); Buffer.memcpyimpl((byte*)pSortedInstances, (byte*)pLeftnode + sortedIndex.Length * sizeof(double), sortedInstances.Length * sizeof(double)); Buffer.memcpyimpl((byte*)pSortedLabels, (byte*)pLeftnode + sortedIndex.Length * sizeof(double) + sortedInstances.Length * sizeof(double), sortedLabels.Length * sizeof(double)); } }
根据经验,Buffer.BlockCopy 和 System.Buffer.memcpyimpl 表现出有竞争力的性能。它们之间的选择往往可以忽略不计。
以上是如何在C#中高效组合多个数组?的详细内容。更多信息请关注PHP中文网其他相关文章!