动态分配内存 [英] Dynamic allocation of memory
问题描述
请考虑以下两个代码
首先:
for (int i = 0; i <10000000; i ++)
{
char * tab = new char [500];
delete []选项卡;
}
第二:
<$ (int i = 0; i< 10000000; i ++)
{
char tab [500]; p $ p>
}
高峰内存使用率几乎相同,但第二个代码运行约20比第一个更快。
问题
是因为在第一个代码数组中存储在堆上,在第二个数组中存储堆栈?
存储在堆上,而在第二个数组中存储堆栈?
是的,堆栈分配比所有第二个代码快得多示例正在做的是移动(添加/减去)堆栈指针,而不是操纵堆。
如果您想了解更多,这两个问题涵盖主题
Lets consider following two codes
First:
for (int i=0;i<10000000;i++)
{
char* tab = new char[500];
delete[] tab;
}
Second:
for (int i=0;i<10000000;i++)
{
char tab[500];
}
The peak memory usage is almost the same, but the second code runs about 20 times faster than the first one.
Question
Is it because in first code array is stored on heap, and in the second one array is stored on stack?
Is it because in first code array is stored on heap, and in the second one array is stored on stack?
Yes, Stack allocation is much faster as all the second code sample is doing is moving (adding/subtracting) the stack pointer rather than manipulating the heap.
If you want to know more, these two questions cover the subject
这篇关于动态分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!