markzzz
markzzz

Reputation: 47945

foreach slower than build string on .cs?

A colleague today told me that is more faster build the whole string on a ascx.cs trought foreach and String Builder (so, write html code in a string) and post it at the end on ascx as <%=myStringGenerateByStringBuilder%>, rather than use foreach directly on ascx, such as :

<% foreach (var thing in things)
   { %>
   <div><p><%= thing.Description %></p></div>
<% }; %>

This because open <% and close %> is very expencive.

Is it true? I don't talk about manage code (which second approch is what I use, very clean and easy), I talk about performance on generate the code.

Upvotes: 3

Views: 216

Answers (5)

Adrian Iftode
Adrian Iftode

Reputation: 15663

Well, some tests:

void Main()
{
    var things = Enumerable
            .Range(1, 2000000)
            .Select(r => new Thing {Description = r.ToString()})
            .ToList();

    var times = Enumerable.Range(1, 10)
        .Select(t => new
            {   
                Method1 = Test(Method1, things),
                Method2 = Test(Method2, things),
            }
    ).ToList();
    var average = new {
            Method1 = TimeSpan.FromMilliseconds( times.Sum(t=>t.Method1.TotalMilliseconds) / times.Count),
            Method2 = TimeSpan.FromMilliseconds( times.Sum(t=>t.Method2.TotalMilliseconds) / times.Count),
    };
    average.Dump();
}

public TimeSpan Test(Action<IEnumerable<Thing>> action, IEnumerable<Thing> things)
{
    var stopWatch = new Stopwatch();
    stopWatch.Start();
    action(things);
    stopWatch.Stop();
    return stopWatch.Elapsed;
}

public void Method1(IEnumerable<Thing> things)
{
    var sb = new StringBuilder();
    using (var stringWriter = new StringWriter(sb) )
    {
        using (var htmlWriter = new HtmlTextWriter(stringWriter))
        {                   
            foreach (var thing in things)
            {
                htmlWriter.Write(thing.Description);
            }
        }
    }   
}


public void Method2(IEnumerable<Thing> things)
{
    var thingsBuilder = new StringBuilder();
    foreach ( var thing in things)
        thingsBuilder.Append(thing.Description);
    var thingsText = thingsBuilder.ToString();
    var sb = new StringBuilder();
    using (var stringWriter = new StringWriter(sb) )
    {
        using (var htmlWriter = new HtmlTextWriter(stringWriter))
        {           
            htmlWriter.Write(thingsText);                   
        }
    }   
}

public class Thing
{
    public string Description {get; set;}
}
// Define other methods and classes here

(use linq pad)

enter image description here

However, I'm in doubt someone would write 2 billions strings in a web page. For smaller lists, there is no difference. Even if I set the Capacity of the StringBuilder it would still be slower. So yes, writing directly many small strings with HtmlTextWriter would be faster than building a string from those strings and then writing it.

Upvotes: 2

sanbornc
sanbornc

Reputation: 776

Also, it would depend on if the site was pre-compiled.

The more important issue IMHO is the lack of maintainability that would be introduced by moving presentation to the code behind. For example if I have to add a class to the div, I should not have to go to the code behind to do this.

Upvotes: 0

Likurg
Likurg

Reputation: 2760

Your colleague was right, i tried same work (i added text in word, for example). I made string using Stringbuilder and foreach and only after added to word it work faster then when i try to added string in foreach.

Upvotes: 0

usr
usr

Reputation: 171178

<%= x %> gets compiled to a call to a TextWriter which has some overhead. It is plausible that building a bigger string first is faster. So is the opposite.

This needs to be measured any any guesses about this without measurements are unfounded.

Upvotes: 1

agent-j
agent-j

Reputation: 27923

You'll need to test this in a live site to be sure because there are many factors.

  • Remember that you are not necessarily just building a string and returning it to the browser.
  • If you are building a large file, you may benefit from the streaming capabilities of asp.net.

Upvotes: 2

Related Questions