I have three methods in c# that runs the same code but with a little bit difference, my first code block is
Stopwatch s = new Stopwatch();
object o = new object();
s.Start();
for (int i = 0; i < 100000000; i++)
{
o.ToString();
o.GetType();
o.GetHashCode();
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds); //3100ms
and this costs 3100ms to run. Then if I make the object initialization inside the for that is increased to 7200ms my code block looks like this;
Stopwatch s = new Stopwatch();
s.Start();
for (int i = 0; i < 100000000; i++)
{
object o = new object();
o.ToString();
o.GetType();
o.GetHashCode();
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds);//7200ms
However, if I initialize my object but not using any method inside this costs for 652ms. And my code is just like this one,
Stopwatch s = new Stopwatch();
s.Start();
for (int i = 0; i < 100000000; i++)
{
object o = new object();
}
s.Stop();
Console.WriteLine(s.ElapsedMilliseconds);//625ms
So I wonder, 3100ms + 625ms is not comparable with 7200ms. What causes that much difference between the first two?
In your second block, you’re calling
GetHashCode()on lots of new objects. From what I remember, the first time a non-overriddenGetHashCode()method is called on an object, a syncblock is allocated for the object. That’s relatively expensive, although subsequent calls toGetHashCodefor the same object (as per your first code) are cheap.So there are three things to bear in mind:
That’s a generalization of course – many methods take the same amount of time however many times you call them, and other ones may be slow for (say) the first 10 calls and fast thereafter. I believe that in the case of
GetHashCode()it’s “first call is expensive” territory though. Try it with a type which overridesGetHashCode()in some simple way and I suspect you’ll find the time taken plummets.Additionally it’s possible that
GetType()takes a while to construct theTypeforobjectthe very first time it’s called – I’m not sure. Basically you’re measuring a bunch of different things together here, which always leads to difficult analysis.