Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 919
Maslow Avatar asked Dec 18 '22 09:12

Maslow


1 Answers

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.

like image 150
Jon Skeet Avatar answered Jan 03 '23 22:01

Jon Skeet