Does boxing create garbage in .NET?

I am wondering if boxing is the value type in an object as a special case or whether the β€œbox” created by .NET becomes garbage (which the GC must collect) after any references to it are deleted.

For example, StringBuilder.AppendFormat () has these overloads:

StringBuilder.AppendFormat(string format, object arg0);
StringBuilder.AppendFormat(string format, object arg0, object arg1);
StringBuilder.AppendFormat(string format, object arg0, object arg1, object arg2);
StringBuilder.AppendFormat(string format, params object[] args);

The presence of additional overloads for calls with 3 or less arguments may indicate that boxing is indeed a special case (or it is calculated from the point of view of performance in order to avoid array construction).

Theoretically, using a simple old reference count, possibly with a pool of reusable boxes, would be a valid implementation, because there could be links from one window to another, only from .NET objects in a field.

+5
source share
3 answers

First, just to clarify: creating an array of object references is not boxing. β€œBoxing” is a term with a very specific meaning in .NET, and I think it's worth sticking to it.

Boxing does create rubbish - or rather, every time you are in the box, it creates a new object, which is likely to eventually become rubbish. (It should not become garbage - you may have a link to this object for the rest of the life of the application, this is quite rare).

However, you may have a boxing cache. Indeed, Java does for small numbers. If you write:

Integer x = 5;
Integer y = 5;
System.out.println(x == y); // Reference comparison

which guarantees printing true.

, - . ( - GC .NET , ) , , .

.NET , Java, , , , ( Java).

, , .NET 2.0 , . , .

+8

, , , , , ( ) , .

3 ( ), , . . " API" .

. StringBuilder.AppendFormat , , object, , . . " Unboxing" . NET: .

+3

.

, , - . , arg_0, arg_1, arg_2, arg_3, , , IL . , , , .

arg_1 ( , arg_0 ).

0

All Articles