logo
CSharp_Prog_Guide

Производительность

По сравнению с простыми операциями присваивания операции упаковки-преобразования и распаковки-преобразования являются весьма затратными процессами с точки зрения вычислений. При выполнении упаковки-преобразования типа значения необходимо создать и разместить новый объект. Объем вычислений при выполнении операции распаковки-преобразования, хотя и в меньшей степени, но тоже весьма значителен.

Boxing Conversion

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object.

Consider the following declaration of a value-type variable:

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

object o = i; // implicit boxing

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.

Boxing Conversion

It also possible to perform the boxing explicitly as in the following example, but explicit boxing is never required:

int i = 123;

object o = (object)i; // explicit boxing