在堆中运行时间 - 堆栈 [英] Running time in Heap - Stack

查看:92
本文介绍了在堆中运行时间 - 堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个代码来计算运行时间。

它正在运行。但是我无法解释:Heap和Stack中的变量之间有什么区别?



我说的是运行时间。

我在Heap中创建了3个变量:a,b,c。

Stack中有3个变量:aa,bb,cc。



我的代码:

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();
    }



这是我的问题:你能告诉我为什么Heap中的运行时间总是比Stack快吗?

谢谢!


Here is my question: Can you tell me why the running time in Heap is always faster than Stack?
Thanks!

推荐答案

在我的系统上,执行时间没有明显的差异。然而,反汇编表明(至少乍一看)增加 aa bb 应该比<$更快c $ c> a 和 b

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:
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







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


这篇关于在堆中运行时间 - 堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆