与嵌套循环和字符串性能问题 [英] Performance issues with nested loops and string concatenations
本文介绍了与嵌套循环和字符串性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以解释为什么这code是这么长时间来运行(即> 24小时): 的行数是5000,而列数为2000(即约10米循环)。
有没有更好的方式来做到这一点????
的for(int i = 0; I< m.rows;我++)
{
对于(INT J = 0; J< m.cols; J ++)
{
textToWrite + =米[I,J]的ToString()+,;
}
//删除最后一个逗号。
textToWrite = textToWrite.Substring(0,textToWrite.Length-2);
textToWrite + = Environment.NewLine;
}
解决方案
由于要创建吨的字符串。
您应该使用StringBuilder的这一点。
StringBuilder的SB =新的StringBuilder();
的for(int i = 0; I< m.rows;我++)
{
布尔第一= TRUE;
对于(INT J = 0; J< m.cols; J ++)
{
sb.Append(M [I,J]);
如果(第一)
{
第一= FALSE;
}
其他
{
sb.Append(,);
}
}
sb.AppendLine();
}
字符串输出= sb.ToString();
Can someone please explain why this code is taking so long to run (i.e. >24 hours): The number of rows is 5000, whilst the number of columns is 2000 (i.e. Approximately 10m loops).
Is there a better way to do this????
for (int i = 0; i < m.rows; i++)
{
for (int j = 0; j < m.cols; j++)
{
textToWrite += m[i, j].ToString() + ",";
}
//remove the final comma.
textToWrite = textToWrite.Substring(0,textToWrite.Length-2);
textToWrite += Environment.NewLine;
}
解决方案
Because you are creating tons of strings.
You should use StringBuilder for this.
StringBuilder sb = new StringBuildeR();
for (int i = 0; i < m.rows; i++)
{
bool first = true;
for (int j = 0; j < m.cols; j++)
{
sb.Append(m[i, j]);
if (first)
{
first = false;
}
else
{
sb.Append(",");
}
}
sb.AppendLine();
}
string output = sb.ToString();
这篇关于与嵌套循环和字符串性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文