stringBuilder vs string concatenation myth of usage...

G

genc_ymeri

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 "different gut feelings"). Some are very specific, this
number (N) of concatenations should not pass never 7 !? Some of these
performance geeks are not far from my cube .....



So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is between
100-200, there is no difference at all in milliseconds (and sometime no diff
in nanoseconds too).

The real difference start at 800+ concatenations. Initially I thought
something wrong with the program I wrote,,,, and then with my testing
methodology. So I decided to copy paste some programs from the articles I
read where is recommended starting to StringBuilder for N => 10. (Amazing
even these tests had their loops number very very high from their
recommandations....100'000)

Well I got the same results for loops less then 200 ! Am I missing something
or is just a fashion of coders to look "high-end performance Pros" ?????

Any input will be very much appreciated.

Thanks in advance,
Genc Ymeri


PS:
We are building a project that has many sql statements wich lines
(concatenations) vary between 20-50. Personally I'm against of using .append
b/c it makes it harder to read through code but of course the performance
comes first if it makes a difference... With my test really shows that there
is no reall difference when this number is between 100-150.
 
C

Chris Fulstow

Hi,

Unless your application is performance-critical, then I'd stick with
the string concatenation and avoid using StringBuilder. I wouldn't
usually say that, but if you're constructing such complex dynamic SQL
queries then they're going to be much easier to read and maintain using
"+" rather than "Append()".

The difference in string performance will probably be negligible
compared with the execution time of your SQL query. If you're really
concerned about performance, maybe first look at converting your
dynamic queries into stored-procedures.

One final point, if you're building your queries in this way then make
sure you protect yourself from SQL injection attacks.

HTH,
Chris
 
J

Josh

I'd suggest also looking at your memory footprint. Performance tuning
is a lot more than just clock cycles. Find CLR profiler and watch your
heap usage in both instances. In the case of simple string
concatenation, you're going to end up creating N instances of the
string whereas in the StringBuilder case you're going to create far
fewer.

I've heard and abide by the rule: If the number of string
concatenations necessary is unknown (as is in your PS case) always use
StringBuilder, otherwise use discretion on your choice.
 
K

Kevin Spencer

It isn't the time of processing that makes it important. It is the
allocation of memory. A string represents an immutable array of char. When
you change the size of a string, you actually must throw away the old array
of char and create a new one. Therefore, when doing a lot of concatenation,
you may be allocating quite a bit of memory. In the long run, it will be
disposed, but depending on the circumstances, it may cause a short-term
memory build-up that is unacceptable.

A StringBuilder, on the other hand, uses an internal array (buffer) in which
the characters are inserted. The length of the string is kept track of by
the object instance. So, you are not necessarily re-allocating memory when
appending or replacing parts of a StringBuilder.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.
 
J

Jon Skeet [C# MVP]

genc_ymeri said:
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 "different gut feelings"). Some are very specific, this
number (N) of concatenations should not pass never 7 !? Some of these
performance geeks are not far from my cube .....

So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is between
100-200, there is no difference at all in milliseconds (and sometime no diff
in nanoseconds too).

100-200 sounds *way* higher than I've seen. Could you post your code?

Note that it depends on the *size* of the concatenations as well as the
number, and the distribution of those sizes.
The real difference start at 800+ concatenations. Initially I thought
something wrong with the program I wrote,,,, and then with my testing
methodology. So I decided to copy paste some programs from the articles I
read where is recommended starting to StringBuilder for N => 10. (Amazing
even these tests had their loops number very very high from their
recommandations....100'000)

Well I got the same results for loops less then 200 ! Am I missing something
or is just a fashion of coders to look "high-end performance Pros" ?????

It sounds like you may have been running the code under the debugger,
or something similar which could have skewed the results.

Of course, it's also possible that you're using .NET 2.0 and that the
tests were run under .NET 1.1... I haven't looked at whether things
have changed in that respect.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

genc_ymeri said:
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 "different gut feelings"). Some are
very specific, this number (N) of concatenations should not pass never 7
!? Some of these performance geeks are not far from my cube .....

I think that it depends of sseveral factor like the size of each string and
the number of comparision, which is absolute faster in one particular
situation? Well you can always try both options in your particular situation
and decide.

I use strings for short concatenations, like the text of a
MessageWindow.Show or an event log entry when I usually concatenate no more
than 4 or 5 strings.

In a loop, always use StringBuilder.

So I did a testing program and I ran it in different PC.
(Note: All software and hardware params in these PCs were different. The
"less powerful" one had 500MB RAM 1.8 Ghz).

My tests showed that when the number of loops of concatenations is
between 100-200, there is no difference at all in milliseconds (and
sometime no diff in nanoseconds too).

IMO this number is WAY to big !!!
Can you post your code?

Also see this article:
http://msdn.microsoft.com/msdnmag/issues/06/01/CLRInsideOut/

PS:
We are building a project that has many sql statements wich lines
(concatenations) vary between 20-50. Personally I'm against of using
.append b/c it makes it harder to read through code but of course the
performance comes first if it makes a difference... With my test really
shows that there is no reall difference when this number is between
100-150.

I would use StringBuilder , if well formatted the code is not that hard to
read.

Again, I think there is something wrong with your code
 
G

genc ymeri

Hi Jon
You really guessed it right :) about two things. (1) I ran it in debug mode
and (2) I have both .net frameworks installed in my machines. (Code was
writen with VS2003)

However switching from debug into release mode the result weren't that much
different.

I hope that everyone here doesn't get me wrong, I'm not saying string
concatenation is faster or the same compare with the stringbuilder
performance, as well the point is not how to get faster sql server results.
I'm trying to say that my testing show that there is almost no difference
for 100-200 string concatenations. So registering a javascript with 10-100
lines with stringBuilder all we really get is an uneasy source code to be
read. Same with sql statements....

Below is my testing code.

Thanks a lot,
Genc Ymeri.



PS:
Code I tested with:

private void btnStringPlus_Click(object sender, System.EventArgs e)
{

int loops = Int32.Parse(tbxLoopNo.Text );
DateTime start = DateTime.Now;
string s = string.Empty;
for (int j = 0; j < loops; j++)
{
s += " hello ";

}

DateTime finish = DateTime.Now;

TimeSpan sp = finish - start;
lblResult.Text = string.Format( " {0} seconds and {1}
milliseconds",sp.Seconds.ToString(), sp.Milliseconds.ToString());
lblResultNano.Text = sp.Ticks.ToString();

}


private void btnAppend_Click(object sender, System.EventArgs e)
{
int loops = Int32.Parse(tbxLoopNo.Text);

DateTime start = DateTime.Now;
StringBuilder sb = new StringBuilder();

for (int j = 0; j <loops ; j++)
{
sb.Append(" hello ");

}
sb.ToString();
DateTime finish = DateTime.Now;

TimeSpan sp = finish - start;
lblResult.Text = string.Format( " {0} seconds and {1}
milliseconds",sp.Seconds.ToString(), sp.Milliseconds.ToString());
lblResultNano.Text = sp.Ticks.ToString();

}
 
G

genc ymeri

I use strings for short concatenations, like the text of a
MessageWindow.Show or an event log entry when I usually concatenate no
more than 4 or 5 strings

Thank you for posting back. I'm really glad to hear the opinion from someone
who uses stringbuilder for more than 5 string concatenations. I really want
to hear your opinion.

I just re-did a test with long lines (more than any screen today can show),
length=500 , loops = 100 and again it made no difference in performance at
all compare with stringbuilder for loops < 100. That tells me unless we want
to heavly manipulate strings or we have a long number of concatenations, in
our usual source code for easy sql statements or common string
concatenations for line with a length of the monitor, the "+" operator will
do the same job with the same cost.

Well, I'm not trying to let other known which is the most appropriate, I'm
just trying to get what are the benefits of using stringbuilder for
concatenation even for very long lines length = 500 when the loops < 100
??? Definately the performance can't be (I don't see any difference). yeah,
probably memory is better managed with the stringbuilder but performance
wise, I see no difference.

Is anything I'm missing still ??????


PS:
The line below is what I used for recent testing . It is concatenated 100
times with result +=s as well with string builder. No significant
performance gains.

s = "hello over there, this is test of string concatenation versus string
builder. Is worthy to use append for less than 100 lines ?hello over there,
this is test of string concatenation versus string builder. Is worthy to use
append for less than 100 lines ?hello over there, this is test of string
concatenation versus string builder. Is worthy to use append for less than
100 lines ?hello over there, this is test of string concatenation versus
string builder. Is worthy to use append for less than 100 lines"









well
 
J

Jon Skeet [C# MVP]

genc ymeri said:
Hi Jon
You really guessed it right :) about two things. (1) I ran it in debug mode
and (2) I have both .net frameworks installed in my machines. (Code was
writen with VS2003)

However switching from debug into release mode the result weren't that much
different.

I hope that everyone here doesn't get me wrong, I'm not saying string
concatenation is faster or the same compare with the stringbuilder
performance, as well the point is not how to get faster sql server results.
I'm trying to say that my testing show that there is almost no difference
for 100-200 string concatenations. So registering a javascript with 10-100
lines with stringBuilder all we really get is an uneasy source code to be
read. Same with sql statements....

To me, that's an indication that you shouldn't have all that text in
your code to start with. Using a resource of some description would
usually make it easier to read and change.

As others have pointed out though, the impact of building the string is
going to be negligible compared with the time taken to execute the
query.
Below is my testing code.

Well, that's certainly not *all* of your testing code - it's a single
method. I note that it's also a method within a form, which can often
affect performance.

Now, about your code itself - that uses DateTime.Now, which has a very
coarse granularity. That's okay, so long as you make sure you test for
a long time - certainly longer than it would take to concatenate 100
strings. Here's a better test:

using System;
using System.Text;

class Test
{
static void Main(string[] args)
{
int iterations = int.Parse(args[0]);
int concatenations = int.Parse(args[1]);
string text = args[2];

int concatLength=-2;
{
DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
string tmp = "";
for (int j=0; j < concatenations; j++)
{
tmp += text;
}
concatLength = tmp.Length;
}
DateTime end = DateTime.Now;
Console.WriteLine ("Concatenation time: {0}", end-start);
}

int builderLength=-1;
{
DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
StringBuilder builder = new StringBuilder();
for (int j=0; j < concatenations; j++)
{
builder.Append(text);
}
builderLength = builder.ToString().Length;
}
DateTime end = DateTime.Now;
Console.WriteLine ("StringBuilder time: {0}", end-start);
}
Console.WriteLine ("Lengths equal? {0}",
concatLength==builderLength);
}
}

Here are some results on my laptop, using .NET 1.1, compiling with
optimisation and running from the command line:

Iterations Concatenations Text += time StringBuilder timer
100000000 1 hello 05.547 16.234
100000000 2 hello 13.531 17.250
100000000 3 hello 23.625 20.984
100000000 5 hello 49.734 37.609
100000000 10 hello 1:59.250 1:11.781
10000000 100 hello 6:28.938 55.125

Now, this isn't a particularly in-depth test (in particular, it always
uses the same text), but it shows that the estimates of about 3-5
concatenations being the break-even point is reasonable - and by the
time we reach 100 concatenations, the difference is *proportionally*
significant. Now, that's very unlikely to make any absolute significant
difference when you're then going to a database, but there *is* a real
difference in the time taken *just for the string concatenation*.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


Maybe posting your code would help, did you compile it in release mode and
run it from outside the IDE?

In total honestly I have never done any benchmark myself, but did you take
a look at the article I sent? IIRC he did include the code used for the
tests.
 
B

Bruce Wood

So registering a javascript with 10-100 lines with stringBuilder all we really get is an uneasy source code to be read. Same with sql statements....

I take issue with your "easy to read" claim. Yes, in your test code,
that's true, but then I have little occasion to concatenate the same
string 100 times to create a long string. Are you really claiming that
this:

string sqlStatement = "select * from my_table where ";
sqlStatement += "field1='";
sqlStatement += value1.ToString();
sqlStatement += "' and field2='";
sqlStatement += value2.ToSTring();
sqlStatement += "'";

is easier to read than this:

StringBuilder sb = new StringBuilder("select * from my_table where ");
sb.AppendFormat("field1='{0}'", value1);
sb.AppendFormat(" and field2='{0}'", value2);
string sqlStatement = sb.ToString();

? I would rather read the second version, myself.
 
J

Jon Skeet [C# MVP]

genc ymeri said:
Thank you for posting back. I'm really glad to hear the opinion from someone
who uses stringbuilder for more than 5 string concatenations. I really want
to hear your opinion.

I just re-did a test with long lines (more than any screen today can show),
length=500 , loops = 100 and again it made no difference in performance at
all compare with stringbuilder for loops < 100. That tells me unless we want
to heavly manipulate strings or we have a long number of concatenations, in
our usual source code for easy sql statements or common string
concatenations for line with a length of the monitor, the "+" operator will
do the same job with the same cost.

No, it won't do the same job with the same cost. It will do the same
cost with several times the cost - but both costs will be tiny. That's
the important thing. If you're only doing it 500 times, there's no way
it's going to be significant. If, however, you're spending most of your
time concatenating strings, then even if you only need to concatenate
batches of 100 strings at a time you'll find there's a very significant
difference.
 
G

genc ymeri

Hi Jon,
Thank you Jon for your testing and sharing your code.

DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
string tmp = "";
for (int j=0; j < concatenations; j++)
{
tmp += text;
}
concatLength = tmp.Length;
}
DateTime end = DateTime.Now;


It's my understanding that your code above, times the Number of total
concatenations N = (iterations) * (concatenations/perIteration)
(I'm ignoring the string tmp = ""; for sake of the point)


So for iterations = 100000000 and for (concatenation/perIteration) = 1 we
have a TOTAL of 100000000 concatenations

I think I mentioned that my total number of concatenations is not more that
100. I reran your test for

iterations = 100, concatenations 1 and text = " hello" = > N = 100
concatenations for the " hello" text.....
...............and showed up absolutely no difference

I reran your program even for long lines, length = 200+;

Results with your program show no difference for N < 100:

00:00:00
00:00:00


In our project, we have no really large text lines, no need for source
files,,,,,, so getting back to the point I'm just doing a copy-past of a sql
statement taken from
our dblayer. (PS) to show what I'm talking about it.

So, Is anyone who really sees any advantage of using stringBuilder to build
a string line as below in PS versus building it with string concatenations
with (+) ???? ( I just got a post from another MVP that even for a
messagebox.show(....) he uses append if he has to concatenate strings more
than 5 time total.)

Thanks a lot and I sincerly appreciate your time and effort helping us,
Genc Ymeri.

PS:

string nl = System.Envirement.NewLine;

//b/c we have not used stringBuilder /.append("..")
// the sqls statement is very readable in the source code too

string sqlGetCabinets =
"select distinct " + nl +
" fc.Filecabinet_ID, " + nl +
" fc.Filecabinet_code, " + nl +
" fc.repository_table, " + nl +
" fc.Filecabinet_desc " + nl +
"from " + nl +
" RS_GROUP_ASSIGNMENTS ga " + nl +
" " + nl
+
" inner join rr_filecabinets fc on " + nl +
" ga.object_id = fc.filecabinet_id " + nl +
" inner join rs_groups g on " + nl +
" g.group_id = ga.group_id " + nl +
" inner join RS_GROUP_DETAILS gd on " + nl +
" gd.group_id = g.group_id " + nl +
" inner join rs_users u on " + nl +
" gd.user_id = u.user_id " + nl +
"where " + nl +
" u.user_name = '" +
aUsername + "'";

try
{
}
catch (....)
{
//sql statemet is logged nice and clean b/c we have used the friendly
newLine separation
// so as soon we we see the sql statements we immidiatly get the problem
log(ex.message + nl + sqlGetCabinets +......);
}







Jon Skeet said:
genc ymeri said:
Hi Jon
You really guessed it right :) about two things. (1) I ran it in debug
mode
and (2) I have both .net frameworks installed in my machines. (Code was
writen with VS2003)

However switching from debug into release mode the result weren't that
much
different.

I hope that everyone here doesn't get me wrong, I'm not saying string
concatenation is faster or the same compare with the stringbuilder
performance, as well the point is not how to get faster sql server
results.
I'm trying to say that my testing show that there is almost no difference
for 100-200 string concatenations. So registering a javascript with
10-100
lines with stringBuilder all we really get is an uneasy source code to be
read. Same with sql statements....

To me, that's an indication that you shouldn't have all that text in
your code to start with. Using a resource of some description would
usually make it easier to read and change.

As others have pointed out though, the impact of building the string is
going to be negligible compared with the time taken to execute the
query.
Below is my testing code.

Well, that's certainly not *all* of your testing code - it's a single
method. I note that it's also a method within a form, which can often
affect performance.

Now, about your code itself - that uses DateTime.Now, which has a very
coarse granularity. That's okay, so long as you make sure you test for
a long time - certainly longer than it would take to concatenate 100
strings. Here's a better test:

using System;
using System.Text;

class Test
{
static void Main(string[] args)
{
int iterations = int.Parse(args[0]);
int concatenations = int.Parse(args[1]);
string text = args[2];

int concatLength=-2;
{
DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
string tmp = "";
for (int j=0; j < concatenations; j++)
{
tmp += text;
}
concatLength = tmp.Length;
}
DateTime end = DateTime.Now;
Console.WriteLine ("Concatenation time: {0}", end-start);
}

int builderLength=-1;
{
DateTime start = DateTime.Now;
for (int i=0; i < iterations; i++)
{
StringBuilder builder = new StringBuilder();
for (int j=0; j < concatenations; j++)
{
builder.Append(text);
}
builderLength = builder.ToString().Length;
}
DateTime end = DateTime.Now;
Console.WriteLine ("StringBuilder time: {0}", end-start);
}
Console.WriteLine ("Lengths equal? {0}",
concatLength==builderLength);
}
}

Here are some results on my laptop, using .NET 1.1, compiling with
optimisation and running from the command line:

Iterations Concatenations Text += time StringBuilder timer
100000000 1 hello 05.547 16.234
100000000 2 hello 13.531 17.250
100000000 3 hello 23.625 20.984
100000000 5 hello 49.734 37.609
100000000 10 hello 1:59.250 1:11.781
10000000 100 hello 6:28.938 55.125

Now, this isn't a particularly in-depth test (in particular, it always
uses the same text), but it shows that the estimates of about 3-5
concatenations being the break-even point is reasonable - and by the
time we reach 100 concatenations, the difference is *proportionally*
significant. Now, that's very unlikely to make any absolute significant
difference when you're then going to a database, but there *is* a real
difference in the time taken *just for the string concatenation*.
 
G

genc ymeri

Are you really claiming that

No, I'm claiming that below string is more readable and has no extra cost to
be build

No of concatenations = 40. Doing it with stringBuilder it has the same
performance.

Am I missing something ????


string nl = System.Envirement.NewLine;

//b/c we have not used stringBuilder /.append("..")
// the sqls statement is very readable in the source code too

string sqlGetCabinets =
"select distinct " + nl +
" fc.Filecabinet_ID, " + nl +
" fc.Filecabinet_code, " + nl +
" fc.repository_table, " + nl +
" fc.Filecabinet_desc " + nl +
"from " + nl +
" RS_GROUP_ASSIGNMENTS ga " + nl +
" " + nl
+
" inner join rr_filecabinets fc on " + nl +
" ga.object_id = fc.filecabinet_id " + nl +
" inner join rs_groups g on " + nl +
" g.group_id = ga.group_id " + nl +
" inner join RS_GROUP_DETAILS gd on " + nl +
" gd.group_id = g.group_id " + nl +
" inner join rs_users u on " + nl +
" gd.user_id = u.user_id " + nl +
"where " + nl +
" u.user_name = '" +
aUsername + "'";

try
{
}
catch (....)
{
//sql statemet is logged nice and clean b/c we have used the friendly
newLine separation
// so as soon we we see the sql statements we immidiatly get the problem
log(ex.message + nl + sqlGetCabinets +......);
}
 
J

Jon Skeet [C# MVP]

It's my understanding that your code above, times the Number of total
concatenations N = (iterations) * (concatenations/perIteration)
(I'm ignoring the string tmp = ""; for sake of the point)

There's more to it than that though. Due to the way concatenation
works, using StringBuilder will give a roughly linear time as the
iterations*concatenations goes up - whereas using string concatenation
will get slower very, very quickly.
So for iterations = 100000000 and for (concatenation/perIteration) = 1 we
have a TOTAL of 100000000 concatenations

Yes - but I hope you understand that will give radically different
results to using iterations = 100000 and concatenations = 1000. Just
try it if you don't believe me.
I think I mentioned that my total number of concatenations is not more that
100. I reran your test for

iterations = 100, concatenations 1 and text = " hello" = > N = 100
concatenations for the " hello" text.....
..............and showed up absolutely no difference

I reran your program even for long lines, length = 200+;

Results with your program show no difference for N < 100:

00:00:00
00:00:00

That doesn't show the relative performance at all though - it just
shows that the test is running too fast to give you any useful results.
Your claim is that StringBuilder and string concatenation are giving
you "the same" performance. That claim isn't true - it's just that your
tests aren't detailed enough to show you the performance difference.

Is an atom the same size as an electron? Absolutely not - but they're
both too small for me to see. The same kind of thing is true here.
In our project, we have no really large text lines, no need for source
files,,,,,, so getting back to the point I'm just doing a copy-past of a sql
statement taken from
our dblayer. (PS) to show what I'm talking about it.

And that's why I said a couple of times that it will be giving you no
significant benefit to use StringBuilder in this case, but that is
*not* the same as your claim that concatenating using StringBuilder and
concatenating using simple string concatenation take the same amount of
time for 100 concatenations. They don't - they just both take such a
short time that it doesn't make much difference.

Put it this way - you could do the whole thing ten times and still see
no difference. That doesn't mean it would do it ten times in the same
amount of time it would take to do it once. There'd still be a factor
of 10 in performance involved - but over such a small period of time
that it's not an issue.
So, Is anyone who really sees any advantage of using stringBuilder to build
a string line as below in PS versus building it with string concatenations
with (+) ???? ( I just got a post from another MVP that even for a
messagebox.show(....) he uses append if he has to concatenate strings more
than 5 time total.)

It may give a readability advantage either way in some cases. As I've
said before however, I'd prefer to have the SQL in a text file built
into the assembly. (In fact, I'd rather have it built up by a tool like
nHibernate in the first place, so I can work in a more object oriented
fashion.)
Thanks a lot and I sincerly appreciate your time and effort helping us,
Genc Ymeri.

PS:

string nl = System.Envirement.NewLine;

//b/c we have not used stringBuilder /.append("..")
// the sqls statement is very readable in the source code too

string sqlGetCabinets =
"select distinct " + nl +
" fc.Filecabinet_ID, " + nl +
" fc.Filecabinet_code, " + nl +
" fc.repository_table, " + nl +
" fc.Filecabinet_desc " + nl +
"from " + nl +
" RS_GROUP_ASSIGNMENTS ga " + nl +
" " + nl
+
" inner join rr_filecabinets fc on " + nl +
" ga.object_id = fc.filecabinet_id " + nl +
" inner join rs_groups g on " + nl +
" g.group_id = ga.group_id " + nl +
" inner join RS_GROUP_DETAILS gd on " + nl +
" gd.group_id = g.group_id " + nl +
" inner join rs_users u on " + nl +
" gd.user_id = u.user_id " + nl +
"where " + nl +
" u.user_name = '" +
aUsername + "'";

That's not actually doing the string concatenation in the way being
talked about in the first place. If nl is a constant, the compiler's
doing it all for you.

See http://www.pobox.com/~skeet/csharp/stringbuilder.html
 
G

genc ymeri

No, it won't do the same job with the same cost. It will do the same
cost with several times the cost - but both costs will be tiny. That's
the important thing. If you're only doing it 500 times, there's no way
it's going to be significant. If, however, you're spending most of your
time concatenating strings, then even if you only need to concatenate
batches of 100 strings at a time you'll find there's a very significant
difference.


Thank a lot Jon and thank you all of you for your input.

Based on all of my tests (writen by me or others), it shows that:

(1) for concatenating 100 lines or less with a
(2) length of [0- 200] characters

the difference of building the result with (+) operator versus the
stringbuilder one is less than 1 nanosecond ( the smalllest unit the
Timespan can track the time).
Concatenation time (ticks) with (+) operator result =+: 0

00:00:00

Concatenation time (ticks) with stringBuilder : 0



Cost in both cases in less than 1 nanoseconds. I can live with that.
Starting to use the stringbuilder at 5 or 7 string concatenations like
below text (I did copy-paste it from my project) is OK as well but
.........................

Once again, thank you very much.

Genc.

PS:

Private Sub GenerateJavascript()
Dim sb As StringBuilder = New StringBuilder(200)
With sb
.Append(vbCrLf)
.Append("<script language=""javascript"">")
.Append(vbCrLf)
.Append("function openAcct(){")
.Append(vbCrLf)
.AppendFormat("myURL=""urlsPROC_ID={0}""", gsRRID)
.Append(vbCrLf)
.Append("myOpts=""width=800,height=600,scrollbars,resizable"";")
.Append(vbCrLf)
.Append("myName=""AcctSelect"";")
.Append(vbCrLf)
.Append("docWindow=window.open(myURL, myName, myOpts);}")
.Append(vbCrLf)
.Append(vbCrLf)
.Append("</script>")
.Append(vbCrLf)
End With
RegisterClientScriptBlock("goAcct", sb.ToString())
end sub
 
J

Jon Skeet [C# MVP]

genc ymeri said:
No, it won't do the same job with the same cost. It will do the same
cost with several times the cost - but both costs will be tiny. That's
the important thing. If you're only doing it 500 times, there's no way
it's going to be significant. If, however, you're spending most of your
time concatenating strings, then even if you only need to concatenate
batches of 100 strings at a time you'll find there's a very significant
difference.


Based on all of my tests (writen by me or others), it shows that:

(1) for concatenating 100 lines or less with a
(2) length of [0- 200] characters

the difference of building the result with (+) operator versus the
stringbuilder one is less than 1 nanosecond ( the smalllest unit the
Timespan can track the time).

You're making an assumption: that the granularity of the clock used by
DateTime.Now is the same as the smallest unit that Timespan can track.
I don't believe that assumption. I don't believe you'll be able to make
two calls to DateTime.Now and have them vary by only a nanosecond.

If it genuinely only took a nanosecond to concatenate 100 strings of 5
characters (much less than your 200 limit), then running my test with
parameters of "1000000000 100 hello" would run in under a second.

Now, if you look at my results, you'll find that running a hundred
times fewer iterations of that took six and a half minutes on my
laptop.

In other words, it looks to me like your estimate is out by a factor of
about 40,000, at least on my computer. Now, my laptop isn't the fastest
thing in the world, but I doubt that yours is 40,000 times as fast.

Could you run my test program with the parameters above and let me know
the results? If I'm right, you might want to leave it running
overnight...
 
G

genc ymeri

Yes - but I hope you understand that will give radically different
results to using iterations = 100000 and concatenations = 1000. Just
try it if you don't believe me.


Hi Jon
I fully understand and I agree with you. I would have expected the same
results - excactly as they showed up with your testing code even before I
started this duscussion. All I wanted to came up is some "rules" when to
start using stringbuilder while keeping a readable code, less keying and the
same performance.

As I personally found out is that starting using the stringbuilder when we
have a total of 7-70 concatenations (linear or not) probably it may not be
that much worthy or at least I do not see gaining that much. Yes,
stringbuilder it may be 20-100 times faster but if difference is less than
one nanoseconds for 7-70 concatenations , I personally due all respect for
other opinions, I can't see how to come up with a rule of using
stringbuilder for concatenations of 7 or 27 strings.

Hoever, thanks a lot, I really appreciate your help.

Genc Ymeri.
 
B

Bruce Wood

I can't see how to come up with a rule of using stringbuilder for concatenations of 7 or 27 strings.

You're right: the rule makes no sense if you're doing it _only once_ in
your code, for example building a SQL statement.

However, if you're concatenating a couple of dozen strings inside a
loop that executes an unknown number of times, then Jon's tests apply
and you should use StringBuilder.

In your particular case this isn't an issue, so using StringBuilder for
a speed advantage doesn't make sense.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top