473,782 Members | 2,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2051
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.goo glegroups.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.WriteLi ne(a);
}

private static void Main(string[] args)
{
string text1 = "ABCDEFG";
Console.WriteLi ne(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.WriteLi ne(a);
}

private static void Main(string[] args)
{
string text1 = "A";
string text2 = "B";
string text3 = "C";
string text4 = text1 + text2 + text3;
Console.WriteLi ne(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.goo glegroups.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.co m> wrote:

"Justin M. Keyes" <ju******@gmail .com> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.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.co m>
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.co m>
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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Bill Butler <qw****@asdf.co m> wrote:

"Justin M. Keyes" <ju******@gmail .com> wrote in message
news:11******** **************@ j33g2000cwa.goo glegroups.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
3647
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
4721
by: Kevin C | last post by:
Quick Question: StringBuilder is obviously more efficient dealing with string concatenations than the old '+=' method... however, in dealing with relatively large string concatenations (ie, 20-30k), what are the performance differences (if any with something as trivial as this) between initializing a new instance of StringBuilder with a specified capacity vs. initializing a new instance without... (the final length is not fixed) ie,
20
11327
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 expressions and I sure there is a lot ways, but I need realy efficient one
23
6257
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
4691
by: genc_ymeri | last post by:
Hi over there, Propably this subject is discussed over and over several times. I did google it too but I was a little bit surprised what I read on internet when it comes 'when to use what'. Most of articles I read from different experts and programmers tell me that their "gut feelings" for using stringBuilder instead of string concatenation is when the number of string concatunation is more then N ( N varies between 3 to max 15 from...
12
2716
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 comparative analysis between the two and, surprisingly, string seems to out perform StringBuilder by a significant amount. A string concatenation takes not quite twice as long using StringBuilder than it does with a string. This doesn't sound right to...
87
5168
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 the library, and other resources related to managed strings are available for download from the CERT web site at: http://www.cert.org/secure-coding/managedstring.html
34
2664
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. ____________ THE OVERVIEW I don't remember where I picked it up, but I remember reading years ago that the simple, obvious Python approach for string concatenation: x = "a" + "b"
13
2680
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 shorter strings. 2.When working with text data longer than 256 bytes. 3.When you want to search and replace the contents of a string 4.When a string is a value type.
0
9643
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10313
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.