Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
StringBuilder vs string concat
Message
De
31/12/2007 09:52:13
Cetin Basoz
Engineerica Inc.
Izmir, Turquie
 
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Divers
Thread ID:
01278482
Message ID:
01278604
Vues:
17
>Hi All, sure most of you know this but I thought I'd post it anyway , I couldnt believe the speed difference, paste this code and compile as console app, then play around increasing the loops
>
>
>
>
>using System;
>using System.Text;
>
>public class Test
>{
>    static void Main()
>    {
>        DateTime start = DateTime.Now;
>        StringBuilder builder = new StringBuilder();
>        for (int i = 0; i < 200000; i++)
>        {
>            builder.Append("!");
>        }
>        string x = builder.ToString();
>        DateTime end = DateTime.Now;
>        Console.WriteLine("Time taken: {0}", end - start);
>
>        Console.WriteLine("Length of x is " + x.Length);
>
>        x = "";
>        start = DateTime.Now;
>
>        for (int i = 0; i < 200000; i++)
>        {
>            x+= "!";
>        }
>
>        end = DateTime.Now;
>        Console.WriteLine("Time taken: {0}", end - start);
>        Console.WriteLine("Length of x is " + x.Length);
>
>    }
>}
>
>
Pete,
It is a known thing I think and makes quite sense. In .Net string type is immutable and a new one is created when it's different. ie:

string x = "hello";
x += " there";

You'd think now in heap only there is a single string "hello there", but now there is two "hello" and "hello there". The more you create new strings the more space you eat from heap. Soon it becomes dog slow to add new ones.

StringBuilder is especially built for such cases. Whenever I need to concatanate more than a few strings I use SB.

Way back, Michel had a thread about it where he was experiencing dramatic slowdown concatanating datatable rows and SB was the answer. Check that out if you can find, there SB was used along with AppendFormat to create a big formatted string.

Cetin
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform