Want to see boxing/unboxing timings - is this code no good?

  • Thread starter Thread starter emma middlebrook
  • Start date Start date
E

emma middlebrook

Hi

Is this class and code snippet not good enough to see the differences
between having a collection of a value type compared with having a
collection of references to a reference type (containing that same
value type)? Using a wrapper around Win32's QueryPerformanceCounter
and some tracing I see very little difference.

class WrappedRectangleF
{
public WrappedRectangleF(RectangleF theRectangleF)
{
_theRectangleF = theRectangleF;
}

public override String ToString()
{
return _theRectangleF.ToString();
}

RectangleF _theRectangleF;
}

FOR BOXING/UNBOXING

int iterations = 100000;
ArrayList container = new ArrayList(iterations);

for (int i = 0; i < iterations; ++i)
{
container.Add(new RectangleF(5, 5, 5, 5));
}
for (int i = 0; i < iterations; ++i)
{
container.ToString();
}

COMPARE WITH THE FOLLOWING ...

int iterations = 100000;
ArrayList container = new ArrayList(iterations);

for (int i = 0; i < iterations; ++i)
{
container.Add(new WrappedRectangleF(new RectangleF(5, 5, 5, 5)));
}
for (int i = 0; i < iterations; ++i)
{
container.ToString();
}

Any ideas?

Emma Middlebrook
(e-mail address removed)
 
In one case you're trying to pass an instance of a value type as an instance
of a reference type. This requires the runtime to box the value type
instance in an instance of a reference-type wrapper. In the other case,
you're essentially doing this work yourself. There shouldn't be much
difference because of the way the test is constructed. What are you trying
to measure?

If you're trying to show the cost of boxing, create two types: one struct
and one class, and contrast the time required to use those types:

struct S { public int val; }
class C { public int val; }
 
There should be no diffeence in performance between implicit autoboxing and
manually using a wrapper since internally basically the same is done.
 
Back
Top