Reputation: 13
I tried to check a perfomance with boxing and without. Here is a code:
public struct p1
{
int x, y;
public p1(int i)
{
x = y = i;
}
}
public class MainClass
{
public static void Main()
{
var al = new List<object>();
var l = new List<p1>();
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
al.Add(new p1(i));
}
p1 b;
for (int i = 0; i < 1000; i++)
{
b = (p1)al[i];
}
Console.WriteLine(sw.ElapsedTicks);
var time = sw.ElapsedTicks;
for (int i = 0; i < 1000; i++)
{
l.Add(new p1(i));
}
p1 v;
for (int i = 0; i < 1000; i++)
{
v = l[i];
}
var t = sw.ElapsedTicks - time;
Console.WriteLine(t);
Console.ReadKey();
}
}
But List of object works faster then List of p1. Why?
1139
9256
1044
6909
Upvotes: 1
Views: 160
Reputation: 564413
I suspect this could be caused by quite a few things.
First, you should always put timings like this into a loop, and run them more than once in the same process. The JIT overhead will occur on the first run, and can dominate your timings. This will skew the results. (Normally, you'll want to completely ignore the first run...)
Also, make sure that you're running this in a release build, run outside of the Visual Studio test host. (Don't hit F5 - use Ctrl+F5 or run from outside VS.) Otherwise, the test host will disable most optimizations and dramatically slow down your results.
For example, try the following:
public static void Main()
{
for (int run = 0; run < 4; ++run)
{
if (run != 0)
{
// Ignore first run
Console.WriteLine("Run {0}", run);
}
var al = new List<object>();
var l = new List<p1>();
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
al.Add(new p1(i));
}
p1 b;
for (int i = 0; i < 1000; i++)
{
b = (p1)al[i];
}
sw.Stop();
if (run != 0)
{
// Ignore first run
Console.WriteLine("With boxing: {0}", sw.ElapsedTicks);
}
sw.Reset();
sw.Start();
for (int i = 0; i < 1000; i++)
{
l.Add(new p1(i));
}
p1 v;
for (int i = 0; i < 1000; i++)
{
v = l[i];
}
sw.Stop();
if (run != 0)
{
// Ignore first run
Console.WriteLine("Without boxing: {0}", sw.ElapsedTicks);
}
}
Console.ReadKey();
}
On my system, by ignoring the first run (JIT issues), and running outside the VS test host in release, I get:
Run 1
With boxing: 99
Without boxing: 61
Run 2
With boxing: 92
Without boxing: 56
Run 3
With boxing: 97
Without boxing: 54
This is obviously dramatically better with the generic, non-boxed version.
Given the very large numbers in your results - I suspect this test was run in VS in Debug mode...
Upvotes: 3
Reputation: 13628
Structs are passed by value not reference. When you auto-box it I believe it will then be passed around by reference. So it is copied multiple times in the second loop.
Upvotes: 0