我昨天进行了一些性能测试,以了解堆栈和堆分配在实践中的差异有多大。从这样的测试中可以预期的是堆分配稍微慢一些或与堆栈分配相当。然而,我惊讶地发现相反的情况。我无法解释为什么,以及它在逻辑上是如何可能的,但堆分配总是稍微快一些(我在优化关闭的情况下进行编译)。
这是一个示例输出:
ticks (stack): 42698
ticks (stack): 43977
ticks (stack): 44024
ticks (stack): 44070
ticks (stack): 45038
ticks (heap): 42588
ticks (heap): 43525
ticks (heap): 43633
ticks (heap): 43681
ticks (heap): 43071
这是一个很小的差异,但它非常一致,它重现了 100% 的时间,有利于堆分配。
谁能解释为什么我会得到这些奇怪的结果?
这是我运行的代码:
#include <vector>
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
struct JJ
{
int c[50];
JJ(int i) { c[5] = 3; c[29] = 4; c[30] = i; c[49] = c[5]; }
};
void fill_direct_stack()
{
vector<JJ> vec;
for (int i=0; i<1000; ++i)
vec.push_back(i);
}
void fill_direct_heap()
{
vector<JJ>* pVec = new vector<JJ>();
for (int i=0; i<1000; ++i)
pVec->push_back(i);
delete pVec;
}
CRITICAL_SECTION cs_print;
void print(string msg, DWORD val)
{
EnterCriticalSection(&cs_print);
cout << msg << val << endl;
LeaveCriticalSection(&cs_print);
}
DWORD __stdcall threadEntry(void*)
{
DWORD ticks1,ticks2;
ticks1 = GetTickCount();
for (int i=0; i<10000; ++i)
fill_direct_stack();
ticks2 = GetTickCount();
print("ticks (stack): ", ticks2 - ticks1);
ticks1 = GetTickCount();
for (int i=0; i<10000; ++i)
fill_direct_heap();
ticks2 = GetTickCount();
print("ticks (heap): ", ticks2 - ticks1);
return 0;
}
int main()
{
cout<<"hi"<<endl;
InitializeCriticalSection(&cs_print);
#define N_THREADS 5
HANDLE thr[N_THREADS];
for (int i=0; i<N_THREADS; ++i)
thr[i] = CreateThread(NULL, 0, &threadEntry, NULL, 0, NULL);
for (int i=0; i<N_THREADS; ++i)
WaitForSingleObject(thr[i], INFINITE);
DeleteCriticalSection(&cs_print);
system("pause");
}