Optimize loop in ASP.Net / C#
I wrote a loop to display each line one by one from a List of string. The problem is that the list contains more that 45,000 lines and its taking a lot of time to create the page for displaying.
Can someone please help in optimizing the code !
List<string> OverrrideLog = lc.getOverrideLog();
List<string> AccessLog = lc.getAccessLog();
foreach (string s in OverrrideLog)
lblOverrideLog.Text += s + 开发者_JAVA技巧"<br/>";
foreach (string s in AccessLog)
lblAccessLog.Text += s + "<br/>";
Here lblOverrideLog and lblAccessLog are literals and each list has more than 22,000 lines.
You can use the String.Join Method (String, IEnumerable):
List<string> OverrrideLog = lc.getOverrideLog();
List<string> AccessLog = lc.getAccessLog();
lblOverrideLog.Text = String.Join("<br />", OverrrideLog);
lblAccessLog.Text = String.Join("<br />", AccessLog);
(See also String.Join vs. StringBuilder: which is faster?)
Untested but try this:
List<string> OverrrideLog = lc.getOverrideLog();
List<string> AccessLog = lc.getAccessLog();
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
foreach(var el in OverrrideLog)
{
sb.Append(el);
sb.Append(" <br />");
}
foreach(var el in AccessLog)
{
sb2.Append(el);
sb2.Append(" <br />");
}
lblOverrideLog.Text = sb.ToString();
lblAccessLog.Text = sb2.ToString();
Edit:
woops, put val
instead of var
You should be using a StringBuilder
.
Concatenating strings like you are creates thousands of temporary ones in memory.
for a exsample
OverrrideLog.ForEach(x=>{
if (sbOverrideLog.Length > 0)
sbOverrideLog.Append("<br />");
sbOverrideLog.Append(x);
});
AccessLog.ForEach(x =>
{
if (sbAccessLog.Length > 0)
sbAccessLog.Append("<br />");
sbAccessLog.Append(x);
});
精彩评论