动态分配内存 [英] Dynamic allocation of memory

查看:132
本文介绍了动态分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下两个代码



首先:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆