2

I'm a beginner in C#, just have some question on string concatenation.

string str = "My name is";
str += "John"

Q1-Does C#(.NET) have the same concept string pool in Java?

Q2- how many string object are created?

  • In *general*, if you want to understand the memory allocation behaviour of code, it's a better investment of your time to learn to use an appropriate *profiling* tool. Certainly better than trying to learn "all of the rules". – Damien_The_Unbeliever Feb 28 '19 at 07:57

2 Answers2

4

Q1-Does C#(.NET) have the same concept string pool in Java?

T̶h̶e̶ ̶a̶n̶s̶w̶e̶r̶ ̶i̶s̶ ̶n̶o̶,̶ ̶u̶s̶i̶n̶g̶ ̶s̶t̶r̶i̶n̶g̶s̶ ̶i̶n̶ ̶C̶#̶ ̶i̶s̶ ̶n̶o̶t̶ ̶l̶i̶k̶e̶ ̶t̶h̶e̶ ̶s̶t̶r̶i̶n̶g̶ ̶p̶o̶o̶l̶ ̶i̶n̶ ̶j̶a̶v̶a̶, each string is its own reference;

Correction : I had to research this for Java... It is conceptually the same thing, i was mistaken about the details of Javas string pool

C# commonly calls it string interning

You can read more about it here at Fabulous Adventures In Coding : Eric Lippert's Erstwhile Blog

String interning and String.Empty

If you have two identical string literals in one compilation unit then the code we generate ensures that only one string object is created by the CLR for all instances of that literal within the assembly. This optimization is called "string interning".

String interning is a CLI feature that reuses a string instance in certain situations :

  1. string literals, created via the ldstr IL command
  2. When invoked explicitly using string.Intern

Q2- how many string object are created?

Because strings in C# are immutable, you get 3 string allocations out of your 2 statements

// 1st string
string str = "My name is";

// 2nd string
// "John"

// 3rd string, which is the concatenation of the first 2
str += "John"
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 1
    Unless the *optimizer* makes the concatenation of *two constants* at the *compile time*: and thus produces an equivalent of `string str = "My name isJoin;"` – Dmitry Bychenko Feb 28 '19 at 07:04
  • @DmitryBychenko I'm not sure they would intern like that, also at least in this case the generated asm doesnt show this kind of optimisation. Worthy comment through – TheGeneral Feb 28 '19 at 07:25
  • @DmitryBychenko that isn't done, though `string str = "My name is" + "John";` **is** complied as if it was `string str = "My name isJohn";` – Jon Hanna Feb 28 '19 at 10:05
1

Yes, there is such a thing.

The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system. source

In your case, I believe there will be three allocations.

Nick
  • 4,787
  • 2
  • 18
  • 24