提供的代碼片段在將三個數組複製到單個三維數組時表現出緩慢的性能。以下是一些實現更快執行速度的替代解決方案:
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.memcpyimpllimp由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中文網其他相關文章!