.net Garbage Collection and Managed Resources

Is memory from primitive data types (int, char, etc.) immediately released after they leave the scope or added to the garbage collection for a later version?

consider the following issues:

For x as integer=0 to 1000 dim y as integer Next 

If this does not add 1000 integers to the garbage collector for cleaning later, how does it handle string objects? will this create 1000 lines to clear later?

 For x as integer=0 to 1000 dim y as string="" Next 

What about structures that contain only int, string, etc. data types.

Classes containing only managed resources?

+4
source share
3 answers

Well, with only two answers there is already misinformation ...

  • A string is not a primitive type
  • String is not a value type
  • Values ​​of type values ​​are not always created on the stack - it depends on where the variable is located. If it is part of a class, it is stored on the heap with the remaining data for this object.
  • Even local variables can be on the heap if they are captured (for example, in anonymous functions and iterator blocks).
  • String literals, such as "", are interned β€” they always allow a single string. This loop does not actually create any rows.

For more information, see my article on what is happening in .NET memory . You can also consider whether it is important or not .

+7
source

Primitive data types (except strings) are value types and are created on the stack, not on the heap. They fly out of the stack when they go out of scope; they are not going to garbage.

Strings are reference types that are allocated on the heap and garbage collected .. NET performs some string memory management optimizations using String Interning . (i.e. you will probably only have one instance of the string "" in memory..NET can do this because the strings are immutable)

+4
source

With the two answers already received, I cannot add in addition to this article , which gives a good description of how garbage collection in .Net works.

+1
source

All Articles