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

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

问题描述

请考虑遵循以下两个代码



首先:

  (int i = 0; i <10000000; i ++)
{
char * tab = new char [500];
delete [] tab;
}

其次:

  for(int i = 0; i <10000000; i ++)
{
char tab [500]
}

峰值内存使用率几乎相同,但第二个代码运行约20

问题

是因为在第一个代码数组中存储在堆上,在第二个数组是存储在堆栈?

解决方案


是因为在第一个代码数组是存储在堆上,而第二个数组存储在堆栈上?


是的,堆栈分配比所有第二个代码sample



如果你想知道更多,这两个问题涵盖了主题




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天全站免登陆