By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,011 Members | 2,968 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,011 IT Pros & Developers. It's quick & easy.

stringBuilder vs string concatenation myth of usage...

P: n/a
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.
Apr 11 '06 #1
Share this Question
Share on Google+
33 Replies


P: n/a
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

Apr 11 '06 #2

P: n/a
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.

Apr 11 '06 #3

P: n/a
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.

"genc_ymeri" <ge********@hotmail.com> wrote in message
news:au******************************@adelphia.com ...
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.

Apr 11 '06 #4

P: n/a
genc_ymeri <ge********@hotmail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 11 '06 #5

P: n/a
Hi,

"genc_ymeri" <ge********@hotmail.com> wrote in message
news:au******************************@adelphia.com ...
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/is.../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
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Apr 11 '06 #6

P: n/a
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();

}







"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
genc_ymeri <ge********@hotmail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Apr 11 '06 #7

P: n/a
> 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
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us> wrote
in message news:u2**************@TK2MSFTNGP02.phx.gbl... Hi,

"genc_ymeri" <ge********@hotmail.com> wrote in message
news:au******************************@adelphia.com ...
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/is.../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
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Apr 11 '06 #8

P: n/a
genc ymeri <ge********@hotmail.com> wrote:
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*.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 11 '06 #9

P: n/a
> 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.

Apr 11 '06 #10

P: n/a
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.

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"genc ymeri" <ge********@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP04.phx.gbl...
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
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us>
wrote in message news:u2**************@TK2MSFTNGP02.phx.gbl...
Hi,

"genc_ymeri" <ge********@hotmail.com> wrote in message
news:au******************************@adelphia.com ...
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/is.../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
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation


Apr 11 '06 #11

P: n/a
genc ymeri <ge********@hotmail.com> wrote:
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.


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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 11 '06 #12

P: n/a
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 [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
genc ymeri <ge********@hotmail.com> wrote:
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*.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Apr 11 '06 #13

P: n/a
>Are you really claiming that
this:


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 +......);
}

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@t31g2000cwb.googlegr oups.com...
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.

Apr 11 '06 #14

P: n/a
genc ymeri <ge********@hotmail.com> wrote:

<snip>
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

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 11 '06 #15

P: n/a
> 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


Apr 11 '06 #16

P: n/a
genc ymeri <ge********@hotmail.com> wrote:
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...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Apr 11 '06 #17

P: n/a
I'd still rather read lines of .AppendFormat myself. :-)

Apr 11 '06 #18

P: n/a
> 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.

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om... genc ymeri <ge********@hotmail.com> wrote:

<snip>
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

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Apr 11 '06 #19

P: n/a
> 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.

Apr 11 '06 #20

P: n/a
> 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.


Absolutely. I'm not even questioning this.

Thanks :)
"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@i40g2000cwc.googlegr oups.com...
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.

Apr 11 '06 #21

P: n/a
Firstly, what is the point of all the white space between the end of the
text for each 'line' and the end of the strings?

Secondly, you are only doing 2 concatenations here. The compiler will
optimize the startic part of the string and treat it as a literal, so that
you effectively end up with (white space excluded):

string sqlGetCabinets = "select
distinct\r\nfc.Filecabinet_ID,\r\nfc.Filecabinet_c ode,\r\nfc.repository_table,\r\nfc.Filecabinet_des c\r\nfrom\r\nRS_GROUP_ASSIGNMENTS\r\n\r\ninner\r\n
join rr_filecabinets fc on\r\nga.object_id = fc.filecabinet_id\r\ninner join
rs_groups g\r\non\r\ng.group_id = ga.group_id\r\ninner join RS_GROUP_DETAILS
gd on\r\ngd.group_id = g.group_id\r\ninner join rs_users u
on\r\ngd.user_id\r\nu.user_id\r\nwhere\r\nu.user_n ame='";

sqlGetCabinetsstring += aUsername + "'";

The string operations are as follows:

Intial allocation and initialisation of sqlGetCabinets

Concatenation of sqlGetCabinets and aUsername
(New instance of sqlGetCabinets is created and old instance is dumped)

Concatenation of sqlGetCabinets and '
(New instance of sqlGetCabinets is created and old instance is dumped)

If you choose to make the strings pretty by imbedding formatting elements
then you have to be prepared to pay the price for it in memory usage and
performance hits.
"genc ymeri" <ge********@hotmail.com> wrote in message
news:eC**************@TK2MSFTNGP04.phx.gbl...
Are you really claiming that
this:


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 +......);
}

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@t31g2000cwb.googlegr oups.com...
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.


Apr 12 '06 #22

P: n/a
Nope, but something like this *is* easier to read:

string sql = "";
sql += "SELECT " + columns + " ";
sql += "FROM " + tables + " ";
sql += "WHERE " + col1 + " = " + condition1 + " AND col2 = " +
condition2;
sql += "ORDER BY " + order;

Better still with syntax highlighting.

Chris

Apr 12 '06 #23

P: n/a

"Stephany Young" wrote...

....
Secondly, you are only doing 2 concatenations here. The compiler
will optimize the startic part of the string and treat it as a
literal, so that you effectively end up with (white space excluded):

string sqlGetCabinets = "select
distinct\r\nfc.Filecabinet_ID,\r\nfc.Filecabinet_c ode,\r\nfc.repository_table,\r\nfc.Filecabinet_des c\r\nfrom\r\nRS_GROUP_ASSIGNMENTS\r\n\r\ninner\r\n
join rr_filecabinets fc on\r\nga.object_id = fc.filecabinet_id\r\ninner
join rs_groups g\r\non\r\ng.group_id = ga.group_id\r\ninner join
RS_GROUP_DETAILS gd on\r\ngd.group_id = g.group_id\r\ninner join rs_users
u on\r\ngd.user_id\r\nu.user_id\r\nwhere\r\nu.user_n ame='";

sqlGetCabinetsstring += aUsername + "'";


I'm not completely sure that it's a good thing if the NewLine is preinserted
at compilation, as I would expect it to give different values on different
platforms.

Anyway, if that's the case, why not write it something like this?

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

That would render it more readable both in the OP's logfile as well as in
the OP's source code.

....or even with the last line as this:

u.user_name = ? ";

....and using a Parameter for the only parameter in the whole statement.

// Bjorn A
Apr 12 '06 #24

P: n/a
> string sql = "";
sql += "SELECT " + columns + " ";
sql += "FROM " + tables + " ";
sql += "WHERE " + col1 + " = " + condition1 + " AND col2 = " +
condition2;
sql += "ORDER BY " + order;
That's a poor example, as it acutally creates 5 string instances. Try:

sql = "SELECT " + columns +
" FROM " + tables +
" WHERE " + col1 + " = " + condition1 +
" AND col2 = " + condition2 +
" ORDER BY " + order;

This example creates a single string instance, while preserving the
readability you want.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

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

"Chris Fulstow" <ch**********@hotmail.com> wrote in message
news:11**********************@e56g2000cwe.googlegr oups.com... Nope, but something like this *is* easier to read:

string sql = "";
sql += "SELECT " + columns + " ";
sql += "FROM " + tables + " ";
sql += "WHERE " + col1 + " = " + condition1 + " AND col2 = " +
condition2;
sql += "ORDER BY " + order;

Better still with syntax highlighting.

Chris

Apr 12 '06 #25

P: n/a
Agreed. Kevin's example will be compiled as a single String.Concat(),
which is far more efficient. Furthermore, if you're concatenating
literal strings then the compiler will also optimise:

string test = "a" + "b" + "c" + "d" + "e";
/* compiler will initialise string as: */
string test = "abcde";

Chris

Apr 12 '06 #26

P: n/a
Hi,
sqlGetCabinetsstring += aUsername + "'";

I'm not completely sure that it's a good thing if the NewLine is
preinserted
at compilation, as I would expect it to give different values on different
platforms.


It will not nl is a variable so that invalidate the possible concatenation
of the string by the compiler.

BTW, it's pretty useless to include it, you dont care about the formatting
when you send the query to the server.

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Apr 12 '06 #27

P: n/a
Hi,


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


Again, can you post the code you are using to test, I find HARD to believe
your results

BTW, in the code you posted before GenerateJavascript() if you write this
using concatenation you will end with two concatenations , no sorry three.
vbCrLf is a constant, so it;s not the same as EnvironMent.NewLine

Post your code and lets analize it together.
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Apr 12 '06 #28

P: n/a

"Ignacio Machin ( .NET/ C# MVP )" wrote...
I'm not completely sure that it's a good thing if the
NewLine is preinserted at compilation, as I would expect
it to give different values on different platforms.
It will not nl is a variable so that invalidate the possible
concatenation of the string by the compiler.


I'm not sure I understand your sentence above.

Other posters in this thread say that the "concatenation" of NewLine *will*
be handled by the compiler, because it's not a variable, but a constant
(which also the documentation says in MSDN).

Do you mean that the OP's use of the intermediate variable 'nl' invalidates
that?

Shouldn't the compiler be able to optimize away that anyway?
BTW, it's pretty useless to include it, you dont care about
the formatting when you send the query to the server.


For the OP, it wasn't useless, as the query itself was logged (with the line
breaks)

// Bjorn A
Apr 12 '06 #29

P: n/a
> Anyway, if that's the case, why not write it something like this?

That's not the point.......

"Bjorn Abelli" <bj**********@DoNotSpam.hotmail.com> wrote in message
news:Ou****************@TK2MSFTNGP04.phx.gbl...

"Stephany Young" wrote...

...
Secondly, you are only doing 2 concatenations here. The compiler
will optimize the startic part of the string and treat it as a
literal, so that you effectively end up with (white space excluded):

string sqlGetCabinets = "select
distinct\r\nfc.Filecabinet_ID,\r\nfc.Filecabinet_c ode,\r\nfc.repository_table,\r\nfc.Filecabinet_des c\r\nfrom\r\nRS_GROUP_ASSIGNMENTS\r\n\r\ninner\r\n
join rr_filecabinets fc on\r\nga.object_id = fc.filecabinet_id\r\ninner
join rs_groups g\r\non\r\ng.group_id = ga.group_id\r\ninner join
RS_GROUP_DETAILS gd on\r\ngd.group_id = g.group_id\r\ninner join rs_users
u on\r\ngd.user_id\r\nu.user_id\r\nwhere\r\nu.user_n ame='";

sqlGetCabinetsstring += aUsername + "'";


I'm not completely sure that it's a good thing if the NewLine is
preinserted
at compilation, as I would expect it to give different values on different
platforms.

Anyway, if that's the case, why not write it something like this?

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

That would render it more readable both in the OP's logfile as well as in
the OP's source code.

...or even with the last line as this:

u.user_name = ? ";

...and using a Parameter for the only parameter in the whole statement.

// Bjorn A

Apr 12 '06 #30

P: n/a
> If you choose to make the strings pretty by imbedding formatting elements
then you have to be prepared to pay the price for it in memory usage and
performance hits.
Well, finally we got back to the point which really I'm not sure why is not
the main focus here.....

Tests show that there is no performance hit for at least up to 100
concatenations for any string with a length up to 200. (or the performance
hit is behind the measurements).

All I wanted to discuss was how come some expert developers have as a
criterion to start using it stringbuilder for 3 concatenations and up.....

Whatever though,
Thanks for you input.

"Stephany Young" <noone@localhost> wrote in message
news:OZ**************@TK2MSFTNGP04.phx.gbl... Firstly, what is the point of all the white space between the end of the
text for each 'line' and the end of the strings?

Secondly, you are only doing 2 concatenations here. The compiler will
optimize the startic part of the string and treat it as a literal, so that
you effectively end up with (white space excluded):

string sqlGetCabinets = "select
distinct\r\nfc.Filecabinet_ID,\r\nfc.Filecabinet_c ode,\r\nfc.repository_table,\r\nfc.Filecabinet_des c\r\nfrom\r\nRS_GROUP_ASSIGNMENTS\r\n\r\ninner\r\n
join rr_filecabinets fc on\r\nga.object_id = fc.filecabinet_id\r\ninner
join rs_groups g\r\non\r\ng.group_id = ga.group_id\r\ninner join
RS_GROUP_DETAILS gd on\r\ngd.group_id = g.group_id\r\ninner join rs_users
u on\r\ngd.user_id\r\nu.user_id\r\nwhere\r\nu.user_n ame='";

sqlGetCabinetsstring += aUsername + "'";

The string operations are as follows:

Intial allocation and initialisation of sqlGetCabinets

Concatenation of sqlGetCabinets and aUsername
(New instance of sqlGetCabinets is created and old instance is dumped)

Concatenation of sqlGetCabinets and '
(New instance of sqlGetCabinets is created and old instance is dumped)

If you choose to make the strings pretty by imbedding formatting elements
then you have to be prepared to pay the price for it in memory usage and
performance hits.
"genc ymeri" <ge********@hotmail.com> wrote in message
news:eC**************@TK2MSFTNGP04.phx.gbl...
>Are you really claiming that
this:


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 +......);
}

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@t31g2000cwb.googlegr oups.com...
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.



Apr 12 '06 #31

P: n/a
I fully agree,
thanks a lot.
"Chris Fulstow" <ch**********@hotmail.com> wrote in message
news:11**********************@v46g2000cwv.googlegr oups.com...
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

Apr 12 '06 #32

P: n/a
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.


yup....it make sense,
thanks a lot.
Apr 12 '06 #33

P: n/a
Hi,
"Bjorn Abelli" <bj**********@DoNotSpam.hotmail.com> wrote in message
news:ei**************@TK2MSFTNGP02.phx.gbl...

"Ignacio Machin ( .NET/ C# MVP )" wrote...
I'm not completely sure that it's a good thing if the
NewLine is preinserted at compilation, as I would expect
it to give different values on different platforms.
It will not nl is a variable so that invalidate the possible
concatenation of the string by the compiler.


I'm not sure I understand your sentence above.


Neither I do :)

I think it was a message I sent by mistake :( , sorry for the mess, it wa
early in the morning and I had no coffee in my MemoryStream yet :)
Other posters in this thread say that the "concatenation" of NewLine
*will* be handled by the compiler, because it's not a variable, but a
constant (which also the documentation says in MSDN).
Well what happens then if you are running in an environment where NewLine is
different? , IF it was compiled AND concatenated in the string it will
display it wrongly in the new platform.
I just checked MSDN and it says textually ( A string containing "\r\n". )
Which IMO it's a mistake.

But as I just saw in another post of the OP , he is not using NewLine (which
is the correct way to do it) but vbCrLf which is indeed a constant
equivalent to "\r\n" , no idea why he posted in the C# NG when he was using
VB.net , but the post is relevant anyway.
Do you mean that the OP's use of the intermediate variable 'nl'
invalidates that?
Yes, if you use a variable you lose the posibility of the compiler
converting it to a literal, just think, what happens if the variable is
changed from another thread? The compiler cannot assure this so I bet it
will not create the literal concatenating all the strings, it will instead
create a bunch of literals.

Shouldn't the compiler be able to optimize away that anyway?


No, for the reason I mentioned above, as soon as you include a variable it
cannot optimize it. At least that is what I think, I haven't check it
though.
BTW, it's pretty useless to include it, you dont care about
the formatting when you send the query to the server.


For the OP, it wasn't useless, as the query itself was logged (with the
line breaks)


You are right, if he logs it it does has a difference, I missed that part.


--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Apr 12 '06 #34

This discussion thread is closed

Replies have been disabled for this discussion.