[英]What's the best way to copy/fill a large array with a smaller array in C#?
我有一個大的 int[] 數組和一個小得多的 int[] 數組。 我想用小數組中的值填充大數組,方法是重復將小數組復制到大數組中直到它已滿(這樣 large[0] = large[13] = large[26]... =小 [0] 等)。 我已經有一個簡單的方法:
int iSource = 0;
for (int i = 0; i < destArray.Length; i++)
{
if (iSource >= sourceArray.Length)
{
iSource = 0; // reset if at end of source
}
destArray[i] = sourceArray[iSource++];
}
但我需要更優雅的東西,希望更快。
使用Array.Copy()
重載讓循環工作,該重載使您可以從一個數組復制到目標數組中的特定索引。
if (sourceArray.Length == 0) return; // don't get caught in infinite loop
int idx = 0;
while ((idx + sourceArray.Length) < destArray.Length) {
Array.Copy( sourceArray, 0, destArray, idx, sourceArray.Length);
idx += sourceArray.Length;
}
Array.Copy( sourceArray, 0, destArray, idx, destArray.Length - idx);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Temp
{
class Program
{
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int[] array2 = new int[213];
for (int i = 0; i < array2.Length; i += array.Length)
{
int length = array.Length;
if ((i + array.Length) >= array2.Length)
length = array2.Length - i;
Array.Copy(array, 0, array2, i, length);
}
int count = 0;
foreach (int i in array2)
{
Console.Write(i.ToString() + " " + (count++).ToString() + "\n");
}
Console.Read();
}
}
}
:)
編輯發現錯誤,如果它們不能彼此分開,將會崩潰。 現在已修復:)
有趣的是,在提供的源陣列中,最成功的答案是最慢的!
我要提出的解決方案是
for (int i = 0; i < destArray.Length; i++)
{
destArray[i] = sourceArray[i%sourceArray.Length];
}
但是當我使用回答問題中的輸入測試性能超過100000次迭代時,它的表現比問者循環差。
這是我的小測試應用程序的輸出
array copy 164ms (Nelson LaQuet's code) assign copy 77ms (MusiGenesis code) assign mod copy 161ms (headsling's code)
for (int i=0;source.Length!= 0 && source.Length!= i;i++)
{
destination[i] = source[i];
}
我從我的舊項目中得到這個並修改了它。 你可能想更改其中的一兩個錯別字,因為其中可能有錯別字
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.