【发布时间】:2010-12-09 06:49:21
【问题描述】:
我有两个 for 循环,它们基本上在两个不同的数组中查找(每个数组的峰值大小约为 2-4k),并根据这些值在第三个数组中设置一个值。出于某种奇怪的原因,这段代码的性能存在两个因素差异,具体取决于我放置两个 for 循环的顺序。
这是第一个设置。它在我的 PC 上执行大约 150 毫秒:
public static int[] SchoolMultiplication(int[] a, int[] b, int numberBase)
{
List<double> times = new List<double>();
TimeTest timeTest = new TimeTest();
int aLen = a.Length;
int bLen = b.Length;
int[,] resultMatrix = new int[a.Length + b.Length, aLen];
int[] result = new int[a.Length + b.Length];
timeTest.Start();
for (int horizontalIndex = 0; horizontalIndex < b.Length; horizontalIndex++)
{
for (int verticalIndex = 0; verticalIndex < a.Length; verticalIndex++)
{
resultMatrix[a.Length + b.Length - 1 - verticalIndex - horizontalIndex, verticalIndex] = a[a.Length - verticalIndex - 1] * b[b.Length - horizontalIndex - 1];
}
}
现在如果我只改变这样的循环顺序
for (int verticalIndex = 0; verticalIndex < a.Length; verticalIndex++)
{
for (int horizontalIndex = 0; horizontalIndex < b.Length; horizontalIndex++)
{
resultMatrix[a.Length + b.Length - 1 - verticalIndex - horizontalIndex, verticalIndex] = a[a.Length - verticalIndex - 1] * b[b.Length - horizontalIndex - 1];
}
}
该方法的总运行时间降至约 400 毫秒。简单的循环顺序交换如何将性能提高近 300%?我想这是某种缓存或指针性能的事情?
【问题讨论】:
-
a和b的长度是多少? -
答案正是@Mike Daniels 提供的链接中的那个。这是一个非常知名的缓存相关问题/优化示例。
-
为了获得更好的多维数组性能,您应该考虑使用指针。
标签: c# arrays optimization