jdl
jdl

Reputation: 6323

What memory usage runs faster... storing an array on the stack or on the heap and accessing it later?

What memory usage runs faster... storing an array on the stack or on the heap and accessing it later: ?

My hunch would be the heap for an array. Don't you have to pop everything off the stack to get to the last item. Where as the heap you can go there directly.

Upvotes: 0

Views: 138

Answers (4)

progrmr
progrmr

Reputation: 77191

Access time, using the array is the same for both, but allocating and reallocating heap takes much longer than on stack.

Upvotes: 0

aroth
aroth

Reputation: 54806

The stack and heap are just logical constructs, there is no actual difference between the two as far as the memory subsystem hardware is concerned. Similarly, pointers do not care if the things they point to reside on the stack or on the heap, nor does the CPU when it dereferences the pointer. Behind the scenes, memory is memory, and there is no difference between stack and heap.

So there should be no difference between the two. If you put your array on the stack and keep a pointer to it, then you don't need to pop everything off the stack to get to it.

One thing you do have to be careful of, however, is that when the currently executing method returns to its caller it will automatically pop the stack and remove anything that it put there. So if you want your data to persist across method invocations you pretty much have to use the heap.

Upvotes: 1

Jim Buck
Jim Buck

Reputation: 20726

Allocating on the stack is faster since allocating stack space amounts to subtracting a value from the stack pointer. Allocating from the heap totally depends on the algorithms used, but they certainly won't be faster than a single instruction subtracting from a stack pointer.

Upvotes: 1

Xavier Holt
Xavier Holt

Reputation: 14619

They're not actually data structures - they're really just shorthand names for the regions of your program's memory where data can be stored. Once the data's stored, you can get to any piece just as quickly as getting to any other piece. Basically:

  • Local variables get stored on the stack, and go away as soon as the function they were created in returns.
  • Anything you create with malloc and friends (C, and Objective-C as well) or new (C++) gets stored on the heap. It sticks around until it's disposed of by free (C) or its destructor (C++).

There's a little bit of OS overhead when adding or removing things from the heap, but unless you're creating and destroying things with an upsetting frequency, you won't notice a difference in performance. Rule of thumb: Only use the heap (malloc / new) for things you want to keep around for a while, and let the compiler take care of the rest.

Hope this helps!

PS: For way more detail than I went into, see this question.

Upvotes: 2

Related Questions