using the string class

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

string object are immutable but if I have this kind of construction se below
1.
will this be done so only one string object is created or will a new string
object
be created to concat This and is and then another string object be created
to concat Thisis and a and so on

1.
string test = "This" + "is" + "a" + "test";

So is the above construction the same as
this construction
string test;
test += "This";
test += "is";
test += "a";
test += "test";

//Tony
 
string test = "This" + "is" + "a" + "test";
So is the above construction the same as
this construction
string test;
test += "This";
test += "is";
test += "a";
test += "test";

No; the C# compiler does the first concatenation for you, so that is
identical to:

string test = "Thisisatest";

Without this compiler trick, it would be a single Concat, so only 1
extra string:

string test = string.Concat("This","is","a","test");

This single Concat call will avoid unnecessary strings - I haven't
checked, but you can imagine that it internally does something like:

StringBuilder result = new StringBuilder();
result.Append("This");
result.Append("is");
result.Append("a");
result.Append("test");
return result.ToString();

(actually, I think it checks the lengths first to allocate the right
amount of space in advance - 11 chars in this case).

With the second construction, this is 4 Concat calls, and lots of
extra intermediary strings:

test = string.Concat(test, "This");
test = string.Concat(test, "is");
test = string.Concat(test, "a");
test = string.Concat(test, "test");

Marc
 
Hello!

string object are immutable but if I have this kind of construction se below
1.
will this be done so only one string object is created or will a new string
object
be created to concat This and is and then another string object be created
to concat Thisis and a and so on

1.
string test = "This" + "is" + "a" + "test";

So is the above construction the same as
this construction
string test;
test += "This";
test += "is";
test += "a";
test += "test";

//Tony

Hi,

In theory yes, only that id does not happens like that, cause the
compiler also try to optimize the code. It will contatenate the
strings for you.
Another different story would be

string spage = " ";
........
string test = "This" + space + "is" + space + "a" + space +
"test";
In this case the compiler cannot do the optimization.

I think (not sure) that the first case is again achived if the space
is declared like
const string space = " ";

But you have to test it :)
 

Ask a Question

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

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

Ask a Question

Back
Top