为什么当我不嵌套它时,我的嵌套 for-if 循环加载时间更长?我可以解决这个问题吗?
本文关键字:嵌套 我可以 解决 问题 时间 循环 为什么 for-if 我的 加载 | 更新日期: 2023-09-27 17:56:04
对不起,如果问题有点模糊,但代码非常复杂,我希望你能有正确的眼睛看到和理解它:)
我将显示 2 个排序代码。代码只是读取一个 excel 表,根据它包含的文本,它会将它们放在一个列表中。例如:我得到了一个 excel 表:
A1 = Peter
D1 = hello
A2 = Frank
D2 = bye
A3 = Jan
D3 = hello
A4 = Obama
D4 = hello
HELLO
的列表将包含:D1、D3、D4BYE
的列表将包含:D2
我首先有这段代码来做它,它运行得非常快:
List<string> ARowList = new List<string>();
List<string> DRowList = new List<string>();
List<string> HELLO = new List<string>();
List<string> BYE = new List<string>();
List<List<string>> AllMeetingsLists = new List<List<string>>();
AllMeetingLists.Add (HELLO);
AllMeetingLists.Add (BYE);
for (int i = 1; !endReach; i++)
{
if (excel_getValue("D"+i).Contains("HELLO"))
{
HELLO.Add(excel_getValue("A"+1) + "said hello how are you")
}
else if (excel_getValue("D"+i).Contains("BYE"))
{
BYE.Add(excel_getValue("A"+1) + "said goodbye have a nice day")
}
Console.WriteLine(excel_getValue("A" + i));
//This goes on for 30 more options of what it can contain
}
我这样做是为了减少代码,但这个运行得慢得多:
List<string> ARowList = new List<string>();
List<string> DRowList = new List<string>();
List<string> HELLO = new List<string>();
List<string> BYE = new List<string>();
List<List<string>> AllMeetingsLists = new List<List<string>>();
AllMeetingLists.Add (HELLO);
AllMeetingLists.Add (BYE);
List<string> ListWithAllSayings = new list<string>();
ListWithAllSayings.Add("hello");
ListWithAllSayings.Add("bye");
for (int j=0;j<ListWithAllSayings.Count;j++)
{
if (excel_getValue("D" +1).Contains(ListWithAllSayings[j]))
{
AllMeetingLists[j].Add("said hello/goodbye: ("A" +i)") // I have to make anther lists off what will be added with the ("A" + i) BUT this is NOT the problem
}
Console.WriteLine(excel_getValue("A" + i));
}
这比其他代码运行得慢。虽然这段代码更容易更改并且更短。(如何)我可以解决这个问题吗?
发生这种情况是因为一旦找到正匹配项,if
- then
- else
的链就会终止,而您的循环会继续尝试其他字符串。如果在大多数时间的前几个常量匹配中找到正确的值,则差异可能很大。
在查找第一项时添加break
将解决此问题。
您应该做的另一件事是将获取单元格的表达式移出循环。您还应该将打印excel_getValue("A" + i)
的行移出循环,因为在修改后的代码中,它会打印在嵌套循环的每次迭代中。
var valueAtDi = excel_getValue("D" +i);
for (int j=0;j<ListWithAllSayings.Count;j++) {
if (valueAtDi.Contains(ListWithAllSayings[j])) {
AllMeetingLists[j].Add("said hello/goodbye: ("A" +i)");
break;
}
}
Console.WriteLine(excel_getValue("A" + i));