I created a code in order to calculate the time of running.
It's working. But I couldn't explain: What is the difference between variables in Heap and Stack?
I'm talking about "running time".
I created 3 variables in Heap: a, b, c.
And 3 variables in Stack: aa, bb, cc.
My code:
class Program
{
private int a = 1;
private int b = 2;
private int c = 0;
static void Main()
{
int aa = 1;
int bb = 2;
int cc = 0;
var sw = new Stopwatch();
var _sw = new Stopwatch();
Program pro = new Program();
for (int k = 0; k < 10; k++)
{
sw.Start();
for (int i = 0; i < 500000000; i++)
{
pro.c += pro.a + pro.b;
}
sw.Stop();
Console.WriteLine("Heap:");
Console.WriteLine("TotalMiliseconds: {0}", sw.Elapsed.TotalMilliseconds.ToString());
Console.WriteLine("__________________________________");
sw.Reset();
_sw.Start();
for (int j = 0; j < 500000000; j++)
{
cc += aa + bb;
}
_sw.Stop();
Console.WriteLine("Stack:");
Console.WriteLine("TotalMiliseconds: {0}", _sw.Elapsed.TotalMilliseconds.ToString());
Console.WriteLine("__________________________________");
_sw.Reset();
}
Console.ReadKey();
}
}
Here is my question: Can you tell me why the running time in Heap is always faster than Stack?
Thanks!