Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many string objects are created?

Tags:

string

c#

object

I have the following C# code:

string stg1 = "String 1";
string stg2 = "String 2";
string stg3 = "String 3";
string stg4;
stg4 = stg1 + stg3;
stg4 = stg4 + stg2 + stg3;
stg4 = "";
stg3 = "";

How many string objects are created?
I think 7 string objects are created: "String 1", "String 2", "String 3", stg1 + stg3, stg4 + stg2 + stg3, "", and "". I wasn't sure if the 4th statement (string stg4;) creates a string object and I read somewhere that assigning a string the empty string "" doesn't create an object but I don't think that's true. What do you guys think?

like image 700
tcox Avatar asked Feb 22 '13 23:02

tcox


1 Answers

I read somewhere that assigning a string the empty string "" doesn't create an object but I don't think that's true. What do you guys think?

That's not quite true. There is most certainly a string instance created for an empty string.

Having said that, there won't be two instances in that code; there will be just one. Unless you disable the setting when compiling, the compiler will find all compile time literal strings that are identical and create just one string object to represent it and give all variables that defined that string the same reference to that one string. This is called "interning".

Note that, by default, string interning is only done for compile time literal strings, not strings generated at runtime. If, at runtime, you generate two strings that are equal, they won't necessarily be references to the same string object.

Other than that, your analysis is correct.

It's also worth noting while you were correct in stating that stg4 + stg2 + stg3 will result in the creation of just one string, you didn't really explain why, and it's not obvious why that's the case.

An initial guess might be that there would be two operations performed here, first stg4 + stg2, which would result in a string, and then that result would be concatenated to stg3 to create the final result. That is not the case though. The compiler will actually generate a single call to string.Concat, passing in all three strings as arguments (Concat is defined as Concat(params string[] args) so it can accept any number of strings) and Concat is smart enough to create just one string, rather than creating strings for the n-1 intermediate values.

like image 112
Servy Avatar answered Oct 06 '22 13:10

Servy