473,385 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

String concatenation -- not the typical question

Hi,

Please read carefully before assuming that this is the same old
question about string concatenation in C#!

It is well-known that the following concatenation produces multiple
immutable String objects for each statement:

String a = "a";
a += "b";
a += "c";
a += "d";

However, I have not seen any source say whether or not the following
statement creates a new String object for each concatenation (i.e.,
each "+" sign):

String b = a + "b" + "c" + "d";

In other words: if the concatenation is done all in one statement, does
the compiler optimize the assignment to b? If the assignment to b had,
say, twenty such concatenations in it, would there be a reason to use
StringBuilder?

Thanks very much.

Justin

Mar 18 '06 #1
9 2031
Two more questions:
What if the terms of the assignment to b were all string literals?
What if the terms of the assignment to b were all string variables?

Thanks!
Justin

Mar 18 '06 #2

"Justin M. Keyes" <ju******@gmail.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
<snip>
However, I have not seen any source say whether or not the following
statement creates a new String object for each concatenation (i.e.,
each "+" sign):

String b = a + "b" + "c" + "d";
This statement in simply converted into concatenation behind the scenes.
<Unverified>
It is also possible that it will optimize away the concatenation of literals altogether.
</Unverified>

In other words: if the concatenation is done all in one statement, does
the compiler optimize the assignment to b?
Yes
If the assignment to b had,
say, twenty such concatenations in it, would there be a reason to use
StringBuilder?


If you are using + as opposed to += you are fine doing it this way
Mar 18 '06 #3
Thanks for your help. For literals I certainly agree, but what if the
statement uses variables? E.G., my statement above has the variable 'a'
as a term.

Mar 18 '06 #4
The compiler is typically pretty smart about these things. Take a look at
your code using reflector:

static void Main(string[] args)
{
string a = "A" + "B" + "C" + "D" + "E" + "F" + "G";
Console.WriteLine(a);
}

private static void Main(string[] args)
{
string text1 = "ABCDEFG";
Console.WriteLine(text1);
}

but it not smarter than your application:

static void Main(string[] args)
{
string a = "A";
string b = "B";
string c = "C";
string d = a + b + c;
Console.WriteLine(a);
}

private static void Main(string[] args)
{
string text1 = "A";
string text2 = "B";
string text3 = "C";
string text4 = text1 + text2 + text3;
Console.WriteLine(text1);
}
and now for a slightly different question and answer:

static void Main(string[] args)
{
string a = "A" + "B" + "C" + "D" + "E" + "F" + "G";
string b = "ABCDEFG";
}

take a look at the debug disassembly and you will see that both a and b are
initialized with the same literal:

string a = "A" + "B" + "C" + "D" + "E" + "F" + "G";
00000029 mov eax,dword ptr ds:[0227307Ch]
0000002f mov edi,eax
string b = "ABCDEFG";
00000031 mov eax,dword ptr ds:[0227307Ch]
00000037 mov esi,eax


--
Andrew Robinson
http://blog.binaryocean.com
"Justin M. Keyes" <ju******@gmail.com> wrote in message
news:11**********************@i39g2000cwa.googlegr oups.com...
Two more questions:
What if the terms of the assignment to b were all string literals?
What if the terms of the assignment to b were all string variables?

Thanks!
Justin

Mar 18 '06 #5
Bill Butler <qw****@asdf.com> wrote:

"Justin M. Keyes" <ju******@gmail.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
<snip>
However, I have not seen any source say whether or not the following
statement creates a new String object for each concatenation (i.e.,
each "+" sign):

String b = a + "b" + "c" + "d";


This statement in simply converted into concatenation behind the scenes.
<Unverified>
It is also possible that it will optimize away the concatenation of
literals altogether.
</Unverified>


Not just possible - guaranteed. Whenever there is a constant expression
(as per the spec definition of "constant expression") the expression is
evaluated at compile-time.

--
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
Mar 18 '06 #6
Justin M. Keyes <ju******@gmail.com> wrote:
Thanks for your help. For literals I certainly agree, but what if the
statement uses variables? E.G., my statement above has the variable 'a'
as a term.


It ends up as a single concatenation: a+"bcd". That's as fast as (or
faster than) using a StringBuilder.

--
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
Mar 18 '06 #7

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Bill Butler <qw****@asdf.com> wrote:

"Justin M. Keyes" <ju******@gmail.com> wrote in message
news:11**********************@j33g2000cwa.googlegr oups.com...
<snip>
> However, I have not seen any source say whether or not the following
> statement creates a new String object for each concatenation (i.e.,
> each "+" sign):
>
> String b = a + "b" + "c" + "d";


This statement in simply converted into concatenation behind the scenes.
<Unverified>
It is also possible that it will optimize away the concatenation of
literals altogether.
</Unverified>


Not just possible - guaranteed. Whenever there is a constant expression
(as per the spec definition of "constant expression") the expression is
evaluated at compile-time.


Thanks Jon,

I wasn't ABSOLUTLY sure so I waffled.
Mar 18 '06 #8
I'm surprised that Jon didn't point you to his page on StringBuilder :)
Here it is.

http://www.yoda.arachsys.com/csharp/stringbuilder.html

The answer is that if the statement uses variables, it is compiled into
a single call to String.Concat(), which does not create intermediate
copies of the string. You get multiple intermediate copies only if you
write this:

string a = b;
a += c;
a += d;
a += e;
....

Mar 18 '06 #9
That is *exactly* what I was looking for.

Bruce Wood, Andrew Robinson, Bill Butler, and Jon Skeet, thanks very
much!

Apr 3 '06 #10

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

Similar topics

5
by: Jonas Galvez | last post by:
Is it true that joining the string elements of a list is faster than concatenating them via the '+' operator? "".join() vs 'a'+'b'+'c' If so, can anyone explain why?
37
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie,...
20
by: hagai26 | last post by:
I am looking for the best and efficient way to replace the first word in a str, like this: "aa to become" -> "/aa/ to become" I know I can use spilt and than join them but I can also use regular...
23
by: Bonj | last post by:
what is the correct form of string concatenation in VB.NET, + or &? Both seem to work, but which is correct? I know it's + in C# and & in VB6, but which in VB.NET?
33
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most...
12
by: Richard Lewis Haggard | last post by:
I thought that the whole point of StringBuilder was that it was supposed to be a faster way of building strings than string. However, I just put together a simple little application to do a...
87
by: Robert Seacord | last post by:
The SEI has published CMU/SEI-2006-TR-006 "Specifications for Managed Strings" and released a "proof-of-concept" implementation of the managed string library. The specification, source code for...
34
by: Larry Hastings | last post by:
This is such a long posting that I've broken it out into sections. Note that while developing this patch I discovered a Subtle Bug in CPython, which I have discussed in its own section below. ...
13
by: Tony Johansson | last post by:
Hello! I read in a book and here is a question and the answer that I'm not satisfied with. When should you use the StringBuilder class instead of the String class. 1.When building a string from...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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

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