Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C#
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!
Posted

1 solution

On my system there isn't a noticeable difference in execution times. However the disassembly suggests (at least at first glance) addition of aa and bb should be faster than that of a and b:
ASM
pro.c += pro.a + pro.b;
000000e0  mov         eax,dword ptr [ebp-78h]
000000e3  mov         eax,dword ptr [eax+0Ch]
000000e6  mov         edx,dword ptr [ebp-78h]
000000e9  add         eax,dword ptr [edx+4]
000000ec  mov         edx,dword ptr [ebp-78h]
000000ef  add         eax,dword ptr [edx+8]
000000f2  mov         edx,dword ptr [ebp-78h]
000000f5  mov         dword ptr [edx+0Ch],eax


ASM
cc += aa + bb;
00000197  mov         eax,dword ptr [ebp-14h]
0000019a  add         eax,dword ptr [ebp-0Ch]
0000019d  add         eax,dword ptr [ebp-10h]
000001a0  mov         dword ptr [ebp-14h],eax
 
Share this answer
 
Comments
user8x86 29-Sep-14 4:14am    
Thanks, Mr. CPallini. But all my tests, the results were the Heap loop faster. Why? Some results for my tests: Heap: 2.0s <=> Stack: 2.2s. Heap: 2.1s <=> Stack 2.4s. Heap: 2.1s <=> Stack: 2.3s. Can you tell me more? Please!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900