Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.StringBuilder limit

I've read that the StringBuilder type has a limit (the default is 16 characters), and when you append some text to it, beyond its limit, a new instance is created with a higher limit and the data is copied to it. I tried that using the following code :

StringBuilder test = new StringBuilder("ABCDEFGHIJKLMNOP",16);
test.Append("ABC");

And the CIL generated for that was :

  .maxstack  3
  .locals init (class [mscorlib]System.Text.StringBuilder V_0)
  IL_0000:  nop
  IL_0001:  ldstr      "ABCDEFGHIJKLMNOP"
  IL_0006:  ldc.i4.s   16
  IL_0008:  newobj     instance void [mscorlib]System.Text.StringBuilder::.ctor(string, int32)
  IL_000d:  stloc.0
  IL_000e:  ldloc.0
  IL_000f:  ldstr      "ABC"
  IL_0014:  callvirt   instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
  IL_0019:  pop
  IL_001a:  ret

Setting the limit to, say, 32 :

StringBuilder test = new StringBuilder("ABCDEFGHIJKLMNOP",32);
test.Append("ABC");

Generated exactly the same IL code. What I expect is creating a new instance in the first case, and changing the value of the instance in the second case, which obviously didn't happen, any clue why?

like image 415
Moayad Mardini Avatar asked Feb 20 '26 11:02

Moayad Mardini


1 Answers

All the fun stuff happens in this line:

IL_0014:  callvirt   instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)

This is where you make the call to the Append() method, but the IL you have posted does not contain the body of that method. Look in the source code for the StringBuilder class (it's released under a license that allows you to have a look), and see what happens within the Append() method.

Spoiler alert! A look at the source code of Append() will reveal that the internal buffer is indeed increased whenever the length of the concatenated string exeeds the current size of the buffer.

like image 98
Jørn Schou-Rode Avatar answered Feb 22 '26 01:02

Jørn Schou-Rode