Optimize the loop in ASP.Net/C#

I wrote a loop to display each line one by one from a list of lines. The problem is that the list contains more than 45,000 lines, and it takes a long time to create a page to display.

Can anyone help in optimizing the code!

List<string> OverrrideLog = lc.getOverrideLog(); List<string> AccessLog = lc.getAccessLog(); foreach (string s in OverrrideLog) lblOverrideLog.Text += s + "<br/>"; foreach (string s in AccessLog) lblAccessLog.Text += s + "<br/>"; 

Here lblOverrideLog and lblAccessLog are literals, and each list contains more than 22,000 lines.

+4
source share
4 answers

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? )

+5
source

Unconfirmed, but try the following:

 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

+4
source

You must use StringBuilder .

Concatenation of strings similar to how you create thousands of temporary in memory.

0
source

for example

  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); }); 
0
source

All Articles