在将测试代码与Sam进行比较后,我确定我们都是对的
- 访问内存(读写)在任何地方都是just as fast—堆栈、全局或堆.
- 然而,它在堆栈上速度最快,在堆上速度最慢.
它是这样的:stack
<;global
<;heap
.(分配时间)
不过,我强烈建议大家在这件事上要小心
- 当您需要频繁创建从不leave函数的数组时(例如,通过传递其引用),使用堆栈将是一个巨大的改进.
- 如果你能回收一个数组,那就尽可能地回收!堆是长期存储对象的最佳场所.(污染全局内存不好;堆栈帧可能会消失)
(Note:1.仅适用于值类型;引用类型将在堆上分配,并且好处将减少到0)
回答问题本身:我在任何大型堆栈测试中都没有遇到任何问题
The section below is my initial answer. It is wrong-ish and the tests aren't correct. It is kept only for reference.
我的测试表明,堆栈分配的内存和全局内存在数组中的使用速度至少比堆分配的内存慢15%(需要120%的时间)!
This is my test code,以下是示例输出:
Stack-allocated array time: 00:00:00.2224429
Globally-allocated array time: 00:00:00.2206767
Heap-allocated array time: 00:00:00.1842670
------------------------------------------
Fastest: Heap.
| S | G | H |
--+---------+---------+---------+
S | - | 100.80 %| 120.72 %|
--+---------+---------+---------+
G | 99.21 %| - | 119.76 %|
--+---------+---------+---------+
H | 82.84 %| 83.50 %| - |
--+---------+---------+---------+
Rates are calculated by dividing the row's value to the column's.
我在Windows 8.1 Pro(带更新1)上测试,使用的是i7 4700 MQ,在.NET 4.5.1下
我使用x86和x64进行了测试,结果是相同的.
Edit:我将所有线程的堆栈大小增加到201MB,样本大小增加到5000万,并将迭代次数减少到5次
Stack-allocated array time: 00:00:00.4504903
Globally-allocated array time: 00:00:00.4020328
Heap-allocated array time: 00:00:00.3439016
------------------------------------------
Fastest: Heap.
| S | G | H |
--+---------+---------+---------+
S | - | 112.05 %| 130.99 %|
--+---------+---------+---------+
G | 89.24 %| - | 116.90 %|
--+---------+---------+---------+
H | 76.34 %| 85.54 %| - |
--+---------+---------+---------+
Rates are calculated by dividing the row's value to the column's.
尽管如此,这个堆栈似乎实际上是getting slower个.