c++ 栈内数组读写效率 v.s. 堆上数组读写效率
函数内定义的数组都在栈内存上。
new 出来的数组在堆内存上(栈上的指针指向它们)。
想知道这两种方法定义的数组的读写效率,写了个小实验程序:
#include<iostream> using namespace std; #include<cmath> #include<time.h> #define n 1000 int main(){ int a[n][n]; int repeat1 = 1E1; clock_t t_start = clock(); for(int i=0;i<repeat1;i++){ for(int p=0;p<n;p++) for(int q=0;q<n;q++) a[q][p]=p; } clock_t t_end = clock(); cout<<" It took me "<<(double)(t_end - t_start)/CLOCKS_PER_SEC<<" s to read stack memory "<<repeat1<<" times repeatedly"<<endl; int **b = new int *[n]; for(int i=0;i<n;i++) b[i] = new int [n]; int repeat2 = repeat1; t_start = clock(); for(int i=0;i<repeat2;i++){ for(int p=0;p<n;p++) for(int q=0;q<n;q++) b[q][p]=p; } t_end = clock(); cout<<" It took me "<<(double)(t_end - t_start)/CLOCKS_PER_SEC<<" s to read heap memory "<<repeat2<<" times repeatedly"<<endl; for(int i=0;i<n;i++) delete [] b[i]; delete [] b; return 0; }
跑出来的结果是
It took me 0.03125 s to read stack memory 10 times repeatedly It took me 0.03125 s to read heap memory 10 times repeatedly
似乎差不多。所以这两种方法,只有征用内存时效率有区别(上一个随笔中,栈上征用和释放,只用了堆上的 1E-6 的时间),读写没有多大区别?