Managing .Net Heap Memory

When creating 2 objects of the same type, the descriptor from the stack memory point will be on the same object in the heap or will point to two separate objects. For clarity, there is a specific question here ...

class Q2 { private static int num = 0; private String prefix; public Q2 (String p) { prefix = p; } public String Msg (String str) { String n; num++; n = num.ToString(); return n + " - " + prefix + str; } } 

Using the appropriate diagram, describe the state of the memory after executing all of the following statements.

  Q2 var1, var2; var1 = new Q2("Question 2"); var2 = new Q2 ("Another view"); 

Here are the answers that I cannot decide between:

1 object:

enter image description here

2 objects:

enter image description here

+6
source share
4 answers

You use the new keyword to create objects in two separate variables, so this always creates a new object on the heap. Thus, the answer will be that it always points to two separate objects.

EDIT : Static variables, such as num , are stored in a special area on the heap called High Frequency Heap , which is not collected by the garbage collector, etc.

+3
source

To help clarify the discussion of heaps here, there are about 8 different heaps that the CLR uses:

  • Loader heap: contains CLR structures and type system
  • High-frequency heap: statics, Method tables, FieldDescs, interface map
  • Low-frequency heap: EEClass, ClassLoader, and lookup tables
  • Stub Heap: stubs for CAS, COM wrappers, P / Invoke
  • A large pile of objects: memory allocations that require more than 85 thousand bytes.
  • GC Heap: user-allocated heap of memory private for the application
  • JIT Code Heap: memory allocated by mscoreee (Execution Engine) and JIT compiler for managed code
  • Process / Base Heap: interop / unmanaged allocations, internal memory, etc.

NTN

+4
source

From MSDN :

There is only one copy of the static member, regardless of how many instances of the class are created.

So, since your class is non-static, you will get multiple instances of your class, but they will refer to the same instance of the instance, one, common, static.

Note You should be VERY careful with code like the one above, because you can get multiple instances of the class that change the value of the common static member, which can lead to unexpected behavior, race conditions, corruption, etc.

If your intention is for the class to be singleton common, then mark the class itself as static so that you only ever have one in your heap at any time.

+2
source

.Net will never automatically combine similar objects.

+1
source

Source: https://habr.com/ru/post/903616/


All Articles