C
C#2d ago
spot

Roslyn String Allocation

I'm interested in seeing exactly how Roslyn allocates strings. I looked through the GitHub a bit, but I couldn't find anything related to my question (Don't know where to look). First, please help me clear any misconceptions that I may have. For the following lines of code
c#
string x = "test";
x = x.ToUpper() + "2";
c#
string x = "test";
x = x.ToUpper() + "2";
What I think I know: - The C# compiler, Roslyn, will allocate memory for all initialized data.. We are given a memory address for the variable x and the contiguous memory is filled with the UTF character codes for "test". - x.ToUpper() is (allocated somewhere new? because strings are immutable), "2" is concatenated to the end of it, and then the contents from the new address is copied to the original address of x. Assuming I used the Debugger to monitor string x or placed in an additional variable to print its address
c#
unsafe{
string x = "test";
string* strPtr1 = &x;
x = x.ToUpper() + "2";
string* strPtr2 = &x;
C.WL(strPtr1);
C.WL(strPtr2);
}
c#
unsafe{
string x = "test";
string* strPtr1 = &x;
x = x.ToUpper() + "2";
string* strPtr2 = &x;
C.WL(strPtr1);
C.WL(strPtr2);
}
Would the memory address for x stay the same? (Unless there was not enough contiguous memory to support increasing its length?) Where can I find the details of this? Would something like this change between versions of C#? Or is this something that would be decided early on and be relatively consistent through the C# life-cycle? Would this change between different operating systems?
5 Replies
Angius
Angius2d ago
You can check the JIT Asm with Sharplab to see what exactly happens under the hood
MODiX
MODiX2d ago
Angius
sharplab.io (click here)
string x = "test";
x = x.ToUpper() + "2";
string x = "test";
x = x.ToUpper() + "2";
Try the /sharplab command! | React with ❌ to remove this embed.
spot
spotOP2d ago
Awesomeee. Thank you. Do you know if the general process for the assembly stays the same between versions/OSes?
Angius
Angius2d ago
I think it does, but I was never much interested in the nitty-gritty of how it works under the hood You could ask in #allow-unsafe-blocks or #roslyn
spot
spotOP2d ago
Bet. Ty

Did you find this page helpful?