Maslow
Maslow

Reputation: 18746

.net Garbage Collection and managed resources

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

consider:

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

If this doesn't add 1000 integers to the garbage collector for clean up later, how does it treat string objects? would this create 1000 strings to clean up later?

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

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

Classes that contain only managed resources?

Upvotes: 4

Views: 1029

Answers (3)

foson
foson

Reputation: 10227

Primitive data types (except string) are value types and are created on the stack and not the heap. They are popped off the stack when they go out of scope; they are not garbage collected.

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1504122

Okay, with only two answers there's already misinformation...

  • String isn't a primitive type
  • String isn't a value type
  • Value type values aren't always created on the stack - it depends on where the variable is. If it's part of a class, it's stored on the heap with the rest of the data for that object.
  • Even local variables can end up on the heap, if they're captured (in anonymous functions and iterator blocks for example)
  • String literals such as "" are interned - they always resolve to the same string. That loop doesn't actually create any strings.

For more info, see my article on what goes where in .NET memory. You might also want to consider whether it's important or not.

Upvotes: 7

Gerrie Schenck
Gerrie Schenck

Reputation: 22378

With the two answers already given there isn't much I can add besides this article which gives a good description on how garbage collection works in .Net.

Upvotes: 1

Related Questions