我有一个大的 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++];
}
但我需要更优雅的东西,并且希望更快。
最佳答案
有趣的是,获胜的答案是所提供的源数组中最慢的答案!
我要提出的解决方案是
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)
关于c# - 在 C# 中用较小的数组复制/填充大数组的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/190045/