Game Development Reference
In-Depth Information
is null . Reference types are allocated on the heap, so the runtime must check to see
that each allocation is successful.
A boxing operation occurs when a value type needs to behave like a reference type.
The Common Language Runtime allocates enough memory to hold a copy of the
value type, including the necessary information to create a valid reference type.
There is a significant amount of performance overhead because of the heap allo-
cation and storage of the value type state. This conversion can occur explicitly
through a cast operation, or implicitly by an assignment operation or a method call.
An unboxing operation occurs when a boxed value type is to be explicitly con-
verted back to a value type on the stack. The Common Language Runtime returns
a pointer to the referenced data, and then the data is typically copied to a location
on the stack through an assignment operation. The boxed value type will still
remain on the heap until the garbage collector is able to reclaim it.
It is important to be aware of areas of your code where large numbers of boxing
and unboxing operations occur. Also be aware that the .NET framework has many
methods and properties that can cause implicit conversions to occur when used
with value types. If a method takes an object as a parameter, then value type
instances will be boxed.
Use Value Types Sensibly
Using value types in performance-critical code can lead to some performance
gain, but only if used correctly. Performance can be significantly decreased if value
types are overused or are used inefficiently. Value types are much faster to instan-
tiate and uninstantiate, and they also take up less space in memory. The size dif-
ference between a value type and a reference type on a 32-bit machine is three
words. This is because reference types store the reference to the object data, a sync
block index, and a method table index. Three words may seem insignificant, but
consider situations where you have a large number of objects. You do need to also
consider the performance implications when value types need to behave as
objects, resulting in a boxing and unboxing operation.
Working with structures can also offer the potential for performance improve-
ments. Classes are specified as auto layout so that the CLR can arrange fields in the
optimal manner for speed and memory size, taking byte alignment into account.
Structures are specified as sequential layout by default, which makes things easy
when passing structures to P/Invoke and unmanaged code, because the layout of
the structure easily maps to the structure in unmanaged code. Performance in this
Search Nedrilad ::




Custom Search