Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic allocation of memory

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?

like image 908
Tomek Tarczynski Avatar asked Feb 14 '10 14:02

Tomek Tarczynski


People also ask

How do you dynamic memory allocate?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.

What is meant by dynamic memory?

A way or organizing different types of data in the phone's memory. Also referred to as Shared memory. Dynamic memory means that all types of data are stored in the same memory (there is no separate memory for photos, ringtones etc.).

What is dynamic memory allocation and its function?

Dynamic Memory Allocation is a process in which we allocate or deallocate a block of memory during the run-time of a program. There are four functions malloc(), calloc(), realloc() and free() present in <stdlib. h> header file that are used for Dynamic Memory Allocation in our system.

What is dynamic memory allocation and its advantages?

Advantages of Dynamic Memory allocationThis allocation method has no memory wastage. The memory allocation is done at run time. Memory size can be changed based on the requirements of the dynamic memory allocation. If memory is not required, it can be freed.


1 Answers

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

  • C++ Which is faster: Stack allocation or Heap allocation
  • What and where are the stack and heap
like image 58
Yacoby Avatar answered Sep 30 '22 07:09

Yacoby