473,902 Members | 3,601 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

StringBuilder much much faster and better than String forconcatenatio n !!!

StringBuilder better and faster than string for adding many strings.

Look at the below. It's amazing how much faster StringBuilder is than
string.

The last loop below is telling: for adding 200000 strings of 8 char
each, string took over 25 minutes while StringBuilder took 40
milliseconds!

Can anybody explain such a radical difference?

The hardware running this program was a Pentium IV with 2 GB RAM.

RL

// stringbuilder much faster than string in concatenation

//////////////
using System;
using System.Collecti ons.Generic;
using System.Linq;
using System.Text;

namespace console1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLi ne("hi \n");
UpdateTime myUpdateTime = new UpdateTime(1000 );
myUpdateTime.Up dateTimeMethod( );
Console.WriteLi ne("times str,sb are: {0}, {1}",
myUpdateTime.tx tConcatTime, myUpdateTime.tx tStringBTime);
}
}
}

/*
* OUTPUT
* results:
* for 1000 iterations: string = 10.01ms; stringbuilder = 0
* for 5000 iterations: string = 410.6ms; stringbuilder = 0
* for 50k iterations: sring = 79013 ms; stringbuilder = 0;
* for 10k iterations : string = 1772.5 ms; stringbuilder = 0;
* for 75k iterations : string = 186237.8ms; stringbuilder = 20.03
ms
* for 100k iterations : string = 334.4k ms (5.6 min); stringbuilder =
20.03 ms;
* for 200k iterations: string = 1515.6k ms (25.3 min); stringbuilder
= 40.06 ms;
*
*
* */
//////////////////////////////
using System;
using System.Collecti ons.Generic;
using System.Linq;
using System.Text;

namespace console1
{
class UpdateTime
{
int txtInterations;
public string txtConcatTime;
public string txtStringBTime;
public UpdateTime(int i)
{
txtInterations = i;
txtConcatTime = "";
txtStringBTime = "";
}

public void UpdateTimeMetho d()
{

int iterations = txtInterations;

string theString = "MyString";

DateTime strCall = DateTime.Now;

string targetString = null;

for (int x = 0; x < iterations; x++)
{
targetString += theString;
}

TimeSpan time = (DateTime.Now - strCall);

txtConcatTime = time.TotalMilli seconds.ToStrin g();

//StringBuilder

DateTime inCall = DateTime.Now;

string theString2 = "MyStrig2";
StringBuilder sb = new StringBuilder(t heString2);

for (int x = 0; x < iterations; x++)
{
sb.Append(theSt ring2);
}

time = (DateTime.Now - inCall);

txtStringBTime = time.TotalMilli seconds.ToStrin g();

}

}
}
/////////////////////
Sep 22 '08
34 3590
raylopez99 wrote:
Göran Andersson wrote:
>Casting to a type that you specify dynamically isn't very useful in a
strongly typed language. You can't do much with the data anyway without
casting the reference to the actual type.

Very good. It explains why C# doesn't have, like C++/CLI, this
function "safe_cast" :
Object ^ obj = safe_cast <Object^(anEnum Here->Current);

Or maybe not.
Actually it doesn't. The reason that there is no "safe_cast" in C# is
that every cast is safe. If you want an unsafe cast you have to do it in
an unsafe code block, and even then you might have to cast it to a void
pointer before casting to a different type to prevent the compiler from
telling you that you are doing something wrong.
Anyway today, via FTM's and Jon Skeet's help, I learned this query,
for iterating through a list having mixed strings and ints and picking
out the first two letters of the strings:
List<objectword s = new List<object{ "green", "blue", 3,
"violet", 5 };

IEnumerable<str ingquery =
words.AsQueryab le().OfType<str ing>().Cast<str ing>().Select(s tr =>
str.Substring(0 ,Math.Min(str.L ength, 2))); //prevents out-of-range
exception and also string cast problem
The OfType extension already returns a typed enumerator, so you don't
need the Cast extension. Also, the OfType is an extension of
IEnumerable, so you don't need the extension AsQueryable to use it on
the List:

IEnumerable<str ingquery = words.OfType<st ring>().Select( str =>
str.Substring(0 ,Math.Min(str.L ength, 2)));

--
Göran Andersson
_____
http://www.guffa.com
Sep 23 '08 #21
On Sep 22, 6:21*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
>
For what it's worth, curious I did a quick test. *I found that the two *
techniques reach near-parity at just 5 concatenations, and StringBuilder *
is definitively faster at 10 concatenations. *At 20, there's no contest..
I'm curious how you did such a quick test, especially since the
DateTime structure is only accurate to at best 10 ms or greater.

You lying *again*, Peter Duniho?

Hahahaha.

RL
Sep 23 '08 #22
>"raylopez99 " <ra********@yah oo.comwrote in message
>news:98******* *************** ************@x3 5g2000hsb.googl egroups.com...
On Sep 22, 6:21 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
>>
For what it's worth, curious I did a quick test. I found that the two
techniques reach near-parity at just 5 concatenations, and
StringBuilde r
is definitively faster at 10 concatenations. At 20, there's no
contest.

I'm curious how you did such a quick test, especially since the
DateTime structure is only accurate to at best 10 ms or greater.
You simply repeat each test about 100,000 times in a loop.
Viola!
Sep 23 '08 #23


Bill Butler wrote:
I'm curious how you did such a quick test, especially since the
DateTime structure is only accurate to at best 10 ms or greater.

You simply repeat each test about 100,000 times in a loop.
Viola!
But Peter said: For what it's worth, curious I did a quick test. I
found that the two
techniques reach near-parity at just 5 concatenations, and StringBuilder
is definitively faster at 10 concatenations. At 20, there's no contest.
Which implies he only tested five concatenations, and up to 20, no
more.

RL
Sep 24 '08 #24
On Sep 24, 10:36*am, raylopez99 <raylope...@yah oo.comwrote:
But Peter said:
For what it's worth, curious I did a quick test. *I found that the two
techniques reach near-parity at just 5 concatenations, and StringBuilder
is definitively faster at 10 concatenations. *At 20, there's no contest.

Which implies he only tested five concatenations, and up to 20, no
more.
You can repeatedly do 20 concatenations though. Doing 20
concatenations 100,000 times is not the same thing as doing 20 *
100,000 concatenations.

Jon

Sep 24 '08 #25


Jon Skeet [C# MVP] wrote:
On Sep 24, 10:36�am, raylopez99 <raylope...@yah oo.comwrote:
But Peter said:
For what it's worth, curious I did a quick test. �I found that the two
techniques reach near-parity at just 5 concatenations, and StringBuilder
is definitively faster at 10 concatenations. �At 20, there's no contest.
Which implies he only tested five concatenations, and up to 20, no
more.

You can repeatedly do 20 concatenations though. Doing 20
concatenations 100,000 times is not the same thing as doing 20 *
100,000 concatenations.

OK, I see. Do 20 loops, store the time difference, and repeat 100k
times. Makes sense.

RL
Sep 24 '08 #26
On Sep 24, 12:28*pm, raylopez99 <raylope...@yah oo.comwrote:
You can repeatedly do 20 concatenations though. Doing 20
concatenations 100,000 times is not the same thing as doing 20 *
100,000 concatenations.

OK, I see. *Do 20 loops, store the time difference, and repeat 100k
times. *Makes sense.
Not quite. The point is to only compare the times at the very start
and end:

1) Start Stopwatch (System.Diagnos tics.Stopwatch)
2) Concatenate string 20 times
3) Repeat step 2 100,000 times
4) Stop Stopwatch
5) Report results

Jon
Sep 24 '08 #27
I'm curious how you did such a quick test, especially since the
DateTime structure is only accurate to at best 10 ms or greater.
Yeah, DateTime subtraction is a terrible way to time stuff. Use the
Stopwatch.Elaps ed.TotalSeconds instead. (And be warned that if you are
running on a motherboard with multiple sockets Stopwatch won't work
right without Vista or manually setting the CPU affinity on your
thread.)
Sep 24 '08 #28
I've been looking for a decent stopwatch, and have checked out various
MSDN articles that say it really can't be done (the one that says "if
you're looking for a metronome, you've come to the wrong place").

If you have code or pseudo code on this "Stopwatch" method, please
post here so I can add it to my bag of tricks aka library.

Thank you,

RL

not_a_commie wrote:
I'm curious how you did such a quick test, especially since the
DateTime structure is only accurate to at best 10 ms or greater.

Yeah, DateTime subtraction is a terrible way to time stuff. Use the
Stopwatch.Elaps ed.TotalSeconds instead. (And be warned that if you are
running on a motherboard with multiple sockets Stopwatch won't work
right without Vista or manually setting the CPU affinity on your
thread.)
Sep 24 '08 #29
raylopez99 <ra********@yah oo.comwrote:
I've been looking for a decent stopwatch, and have checked out various
MSDN articles that say it really can't be done (the one that says "if
you're looking for a metronome, you've come to the wrong place").

If you have code or pseudo code on this "Stopwatch" method, please
post here so I can add it to my bag of tricks aka library.
As I said before, see System.Diagnost ics.Stopwatch. (It's not a method,
it's a type.)

Simple example:

using System;
using System.Diagnost ics;

class Test
{
static void Main()
{
Stopwatch sw = Stopwatch.Start New();
// Do something expensive
string x = "";
for (int i=0; i < 100000; i++)
{
x += " "; // Eek!
}

sw.Stop();
Console.WriteLi ne("Elapsed time: {0}ms",
sw.ElapsedMilli seconds);
}
}

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 24 '08 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

37
4741
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie, 20-30k), what are the performance differences (if any with something as trivial as this) between initializing a new instance of StringBuilder with a specified capacity vs. initializing a new instance without... (the final length is not fixed) ie,
16
410
by: Alvin Bruney | last post by:
Is string builder intelligent enough to handle concats without behaving like string? Consider myStringBuilder.Append("one" + "two") what does the '+' do here? Because this syntax is also legal but what is the cost compared to myStringBuilder.Append("one"); myStringBuilder.Append("two");
14
15061
by: Bob | last post by:
I have a function that takes in a list of IDs (hundreds) as input parameter and needs to pass the data to another step as a comma delimited string. The source can easily create this list of IDs in a comma-delimited string or string array. I don't want it to be a string because I want to overload this function, and it's sister already uses a string input parameter. Now if I define the function to take in a string array, it solves my...
33
4713
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most of articles I read from different experts and programmers tell me that their "gut feelings" for using stringBuilder instead of string concatenation is when the number of string concatunation is more then N ( N varies between 3 to max 15 from...
26
3230
by: Hardy Wang | last post by:
Hi all, I know it is better to handle large string with a StringBuilder, but how does StringBuilder class improve the performance in the background? Thanks! -- WWW: http://hardywang.1accesshost.com ICQ: 3359839 yours Hardy
10
4428
by: =?Utf-8?B?RGFyYSBQ?= | last post by:
Can some one suggest me as why StringBuilder class is better than Strings? -- Never say, Give up
0
9845
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10866
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9672
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8045
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7204
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5892
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6084
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4305
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.