[Mono-devel-list] Performance w/ boxing

Ben Maurer bmaurer at users.sourceforge.net
Thu Feb 19 19:57:24 EST 2004


On Thu, 2004-02-19 at 18:07, Jaroslaw Kowalski wrote:
> Is it possible to share the boxed objects in case when they hold the same
> value? Considering the following statements:
> 
> object o1 = 2;
> object o2 = 2;
> 
> Is it possible to have o1 and o2 refer to the same object on heap? What
> about lock() on such objects?

Not at all. According to the CLI spec:

'Unlike box, which is required to make a copy of a value type for use in
the object, unbox is not required to copy the value type from the
object. Typically it simply computes the address of the value type that
is already present inside of the boxed object.'

In short, you basically get back a pointer to the value. A consequence
of this is that you can modify the value inside the box.

So, in pseudo code, this:

object o = 2;
object b = o;
((BoxedInt) o).IntValue = 3;
Console.WriteLine ("O: {0}; B: {1}", o, b);

will print

O: 3; B: 3

So, lets say, with your idea, we did:
object o = 2;
object b = 2;
((BoxedInt) o).IntValue = 3;
Console.WriteLine ("O: {0}; B: {1}", o, b);

It would print the same as above. This is not correct.

Also, even if it were correct, there are threading issues, etc.

-- Ben




More information about the Mono-devel-list mailing list