Subscribe

RSS Feed (xml)

Powered By

Powered by Blogger

Google
 
xnahelp.blogspot.com

Kamis, 03 April 2008

Managing Memory

There are two types of objects in the .NET Framework: reference and value. Examples of
value types are enums, integral types (byte, short, int, long), floating types (single, double,
float), primitive types (bool, char), and structs. Examples of objects that are reference
types are arrays, exceptions, attributes, delegates, and classes. Value types have their data
stored on the current thread’s stack and the managed heap is where reference types find
themselves.
By default, when we pass variables into methods we pass them by value. This means for
value types we are actually passing a copy of the data on the stack, so anything we do to
that variable inside of the method does not affect the original memory. When we pass in
a reference type we are actually passing a copy of the reference to the data. The actual
data is not copied, just the address of the memory. Because of this, we should pass large
CHAPTER 3 40 Performance Considerations
value types by reference instead of by value when appropriate. It is much faster to copy
an address of a large value type than its actual data.
We use the ref keyword to pass the objects as reference to our methods. We should not
use this keyword on reference types as it will actually slow things down. We should use
the keyword on value types (like structs) that have a large amount of data it would need
to copy if passed by value.
The other thing to note is that even if we have a reference type and we pass it into a
method that takes an object type and we box (implicitly or explicitly), then a copy of the
data is actually created as well—not just the address to the original memory. For example,
consider a class that takes a general object type (like an ArrayList’s Add method). We pass
in a reference type, but instead of just the reference being passed across, a copy of the
data is created and then a reference to that copy of the data is passed across. This eats up
memory and causes the garbage collector to run more often. To avoid this we need to use
generics whenever possible.

0 komentar: