Search code examples
c#.netvisual-studiogarbage-collectionmemory-profiling

Value of "Objects (Diff)" column (Diagnostic Tools) is not changed once a new string has been instantiated


Actually, it is the first time when I am interested in memory monitoring via Diagnostic Tool built-in Visual Studio. Hence, maybe I've used it in the wrong way.

I made 3 memory snapshots while debugging the following code:

enter image description here

  1. First ID=1 snapshot when the breakpoint was at 7 line;
  2. Second ID=2 snapshot when the breakpoint was at 8 line;
  3. And last third ID=3 snapshot when the breakpoint was at 9 lines of code.

My question is why after a new string object str2 allocation the Objects and Heap Size values are not changed — they are still 168/57.80? I expected incrementing of them.


Solution

  • You are not seeing the difference because the application is not allocating memory for the two strings. When you have string literals in your code ("text in quotes is a string literal") then that string is embedded within your assembly (.exe or .dll depending on the project type). When the application is loaded your assembly is completely loaded in memory and your literal text is already in memory. When you assign a variable to this string literal you are simply making the variable point to that memory.
    If you want to allocate then you have to generate a new string and not use a string literal. Try creating a string using the string constructor which repeats a letter:

        var str = new String('a', 20);
    

    You should see an allocation occur.

    Note: Be aware that compiler is pretty smart and if you try to force an allocation by concatenating two string literals ("this" + " is " + " a string") the compiler might just generate a new string literal during compilation and there will again be no allocation and runtime.