我尝试在堆内存和栈内存中为10^7个整数分配空间,以查看哪种方式更快。显然,在堆内存中分配速度更快,但我不理解原因。
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
int main()
{
high_resolution_clock::time_point t1 = high_resolution_clock::now();
int *p = new int[1e7];
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << duration / 1e6 << "\n"; // 5e-06
t1 = high_resolution_clock::now();
vector<int> v(1e7);
t2 = high_resolution_clock::now();
duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << duration / 1e6 << "\n"; // 0.112284
return 0;
}
std::vector
也会在堆上分配其数据!只有少数成员变量,包括指针,实际上驻留在堆栈上;尝试使用sizeof(std::vector<int>)
,以获取实际分配在堆栈上的字节数... - Aconcagua