Prev | Current Page 121 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

However, in other ways reference types are
more performant??”parameter passing, assignment, returning values and similar operations
only require 4 or 8 bytes to be copied (depending on whether you??™re running
52 CHAPTER 2 Core foundations: building on C# 1
the 32-bit or 64-bit CLR) rather than copying all the data. Imagine if ArrayList were
somehow a ???pure??? value type, and passing an ArrayList expression to a method
involved copying all its data!
MYTH #2: ???REFERENCE TYPES LIVE ON THE HEAP, VALUE TYPES LIVE ON THE STACK???
This one is often caused just by laziness on the part of the person repeating it. The
first part is correct??”an instance of a reference type is always created on the heap. It??™s
the second part that is problematic. As we??™ve already noted, a variable??™s value lives
wherever it??™s declared??”so if you have a class with an instance variable of type int, that
variable??™s value for any given object will always be where the rest of the data for the
object is??”on the heap. Only local variables (variables declared within methods) and
method parameters live on the stack.
NOTE Are these concepts relevant now? It??™s arguable that if you??™re writing managed
code, you should let the runtime worry about how memory is best
used. Indeed, the language specification makes no guarantees about
what lives where; a future runtime may be able to create some objects on
the stack if it knows it could get away with it, or the C# compiler could
generate code that hardly uses the stack at all.


Pages:
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133