difference between dynamic allocation static allocation

1.6k Views Asked by At

MY question is In any programming language is dynamic memory allocation faster than static memory allocation?

int main(int, char**)
{
    int *pa = new int; // faster than
    int a;             // ?
    return 0;
}
2

There are 2 best solutions below

5
On

This is not static allocation but automatic allocation (your variables are locals). Static allocation is for static local, and global (file-scope) variables.

Nonetheless, dynamic allocation is never faster. In C and C++ it's a system call, which are slow.

Even if it wasn't so slow, automatic and static allocation are instantaneous. Static allocation happens at program start, and is just more space reserved for your process by the OS. Automatic allocation is just the stack pointer going a few bytes further when your function gets called. In either case, nothing more (CPU-wise) is done than if you hadn't allocated your variable.

0
On

is dynamic memory allocation faster than static memory allocation

What you are comparing is allocating on the stack (automatic) vs allocating on the heap (dynamic), static allocation is not involved here.

Allocating on the stack is fast in C++, once function is entered the space for automatic variables has been allocated. It is just a matter of subtracting the size of the required space from the stack pointer.

Heap allocation is generally slower than allocating on the stack. It involves carving out chunks of memory from the OS and then breaking down those chunks into smaller pieces to serve user's allocation requests. Heap managers can be pretty complex libraries, see memory management.