在函数内直接定义多维数组,即可在栈上开辟内存。
用栈上指针 new 出堆内存,定义多维数组,即在堆上开辟内存。
可以比较这两种的速度,做个小实验,心里有个数。
代码如下:
#include<iostream> using namespace std; #include<cmath> #include<time.h> #define n 1000 void open_stack_memory(){ int a[n][n]; } void open_heap_memory(){ int **a = new int *[n]; for(int i=0;i<n;i++) a[i] = new int [n]; for(int i=0;i<n;i++) delete [] a[i]; delete [] a; } int main(){ int repeat1 = 1E7; clock_t t_start = clock(); for(int i=0;i<repeat1;i++) open_stack_memory(); clock_t t_end = clock(); cout<<" It took me "<<(double)(t_end - t_start)/CLOCKS_PER_SEC<<" s to open stack memory "<<repeat1<<" times repeatedly"<<endl; int repeat2 = 1E1; t_start = clock(); for(int i=0;i<repeat2;i++) open_heap_memory(); t_end = clock(); cout<<" It took me "<<(double)(t_end - t_start)/CLOCKS_PER_SEC<<" s to open and delete heap memory "<<repeat2<<" times repeatedly"<<endl; return 0; }
运行结果为:
It took me 0.03125 s to open stack memory 10000000 times repeatedly It took me 0.0625 s to open and delete heap memory 10 times repeatedly
所以,直接征用栈内存,是 new 出堆内存的 1E6 倍速度。