SwiftMango
SwiftMango

Reputation: 15284

Does allocation on the heap affect the access performance?

As known:

ptr = malloc(size);

or in C++

ptr = new Klass();

will allocate size bytes on the heap. It is less efficient than on the stack.

But after the allocation, when we access it:

foo(*ptr);

or

(*ptr)++;

Does it have the same performance as data on the stack, or still slower?

Upvotes: 1

Views: 177

Answers (4)

JackCColeman
JackCColeman

Reputation: 3807

Efficiency considerations are important when comparing an algorithm that runs in O(n^2) time versus O(nlogn), etc.

Comparing memory storage accesses, both algorithms are O(n) or O(k) and usually is is NOT possible to measure any difference.

However, if you are writing some code for the kernel that is frequently invoked than a small difference might become measurable.

In the context of this question, the real answer is that it really doesn't matter, use whichever storage makes your program easy to read and maintain. Because, in the long run the cost of paying humans to read your code is more than the cost of a running a cpu for a few more/or less instructions.

Upvotes: 0

Narayan
Narayan

Reputation: 48

Stack is much faster than Heap since it involves as simple as moving the stack pointer. stack is of fixed size. in contrast to Heap, user need to manually allocate and de-allocate the memory.

Upvotes: -2

John Bode
John Bode

Reputation: 123468

The only way to definitively answer this question is to code up both versions and measure their performance under multiple scenarios (different allocation sizes, different optimiziation settings, etc). This sort of thing depends heavily on a lot of different factors, such as optimization settings, how the operating system manages memory, the size of the block being allocated, locality of accesses, etc. Never blindly assume that one method is more "efficient" than another in all circumstances.

Even then, the results will only be applicable for your particular system.

Upvotes: 2

Mats Petersson
Mats Petersson

Reputation: 129374

It really depends on what you are comparing and how.

If you mean is

ptr = malloc(10 * sizeof(int)); 

slower than:

int arr[10]
ptr = arr; 

and then using ptr to access the integers it points at?

Then no.

If you are referring to using arr[0] instead of *ptr in the second case, possibly, as the compiler has to read the value in ptr to find the address of the actual variable. In many cases, however, it will "know" the value inside ptr, so won't need to read the pointer in itself.

If we are comparing foo(ptr) and foo(arr) it won't make any difference at all.

[There may be some penalty in actually allocating on the heap in that the memory has to be "committed" on the first use. But that is at most once for each 4KB, and we can probably ignore that in most cases].

Upvotes: 1

Related Questions