gpt4 book ai didi

c# - 需要有关提高 C# 代码性能的建议

转载 作者:太空宇宙 更新时间:2023-11-03 21:59:47 25 4
gpt4 key购买 nike

我有函数,调用非常频繁。此函数内部有两个嵌套的 for 循环。每个 for 循环从 0 迭代到 900。代码如下所示:

 for (int j = 0; j < width; j++)
{
for (int k = 0; k < height; k++)
{
switch (Dim2[j * width + k])
{
case 0:
cwA = Dim0[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
ccwA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
oppA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
cwB = Dim3[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
ccwB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
oppB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
break;

case 1:
cwA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
ccwA = Dim0[j * width + ((k == 0) ? (height - 1) : (k - 1))];
oppA = Dim0[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
cwB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + k];
ccwB = Dim3[j * width + ((k == 0) ? (height - 1) : (k - 1))];
oppB = Dim3[((j == (width - 1)) ? 0 : (j + 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
break;

case 2:
cwA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + k];
ccwA = Dim0[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
oppA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
cwB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + k];
ccwB = Dim3[j * width + ((k == (height - 1)) ? 0 : (k + 1))];
oppB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == (height - 1)) ? 0 : (k + 1))];
break;

case 3:
cwA = Dim0[j * width + ((k == 0) ? (height - 1) : (k - 1))];
ccwA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + k];
oppA = Dim0[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
cwB = Dim3[j * width + ((k == 0) ? (height - 1) : (k - 1))];
ccwB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + k];
oppB = Dim3[((j == 0) ? (width - 1) : (j - 1)) * width + ((k == 0) ? (height - 1) : (k - 1))];
break;
}
woll = (((oppB + ccwB) + cwB) + Dim3[j * width + k]) > 0;
collision = ((Dim0[j * width + k] == oppA) && (cwA == ccwA)) && (Dim0[j * width + k] != cwA);
Dim6[j * width + k] = (short)(3 - Dim2[j * width + k]);
if (woll || collision)
{
Dim4[j * width + k] = Dim0[j * width + k];
}
else
{
Dim4[j * width + k] = _phase ? cwA : ccwA;
}
}
}

执行这些 for 循环需要大约 0.1 秒,这太慢了。我用一维数组替换了二维数组,这显着提高了性能。代码还有其他性能改进吗?如果我将它迁移到 C++,它会工作得更快吗?我应该使用任何其他语言来进行数组操作吗?你有什么建议?
提前致谢,
山姆

最佳答案

height - 1j + 1width - 1j * width 重构为变量,因此它们只计算一次。这会有所帮助。事实上,您可以添加到此列表:

(j == (width - 1)) ? 0 : (j + 1)

关于c# - 需要有关提高 C# 代码性能的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10688524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com