1

/* I have two classes. One is allocating memory on stack for its members while other is allocating on heap. See the below code snippet.*/

class A_Heap {

public:
    A_Heap()

    {
        ptr = new char[256];
        int_ptr = new int[1024];
    }

private:

    char * ptr;
    int * int_ptr;
    int abc;
    char ch;

};

class A_Stack {

public:
    A_Stack()
    {
    }

private:

    char ptr[256];
    int int_ptr[1024];
    int abc;
    char ch;
};

/*class A_Heap will be less efficient as allocate memory on heap causing two more context switch from user to kernel mode? */

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 2
    Efficient in what sense? Time? Memory? Stack space is limited, so allocating there is not always an option. – Yksisarvinen May 11 '20 at 13:44
  • 2
    You're getting into micro-optimizations, which are almost never worth the time to bother with them (unless you actually *measured* this to be a top-two bottleneck in your program). If you know the size at compile-time, consider using `std::array`, and if not then use `std::vector`. And for strings, always use `std::string` (or possibly `std::string_view`). – Some programmer dude May 11 '20 at 13:46
  • 1
    When in doubt, use the automatic store aka the stack. Prefer `std::vector` or `std::array` to raw arrays. And lastly, prefer smart pointers to raw pointers. Your time is probably better invested in areas other than micro-optimizations. – Ron May 11 '20 at 13:46
  • efficient with respect to time. – Chandan Srivastava May 11 '20 at 13:46
  • 1
    Stack allocation basically involves just an update of the stack-relevant register. Heap allocation is much more complicated and likely will be many times slower, such as [142 times in this demo](http://quick-bench.com/Lw5ZdnqTDvwENN_aWTnnWnoUCZo). – Daniel Langr May 11 '20 at 14:01
  • I wouldn't use `A_Stack` as it seems to present an excessive risk of blowing out the stack, in my opinion. Additionally, consider whether you ever want to `std::move` a `A_Stack`. You'll have a price to pay to use it with the most common containers. – François Andrieux May 11 '20 at 14:12
  • Thanks @DanielLangr for sharing the link. From that link, now I strongly believe that stack is more efficient. My question is specif to my case. Because I am not able to see the performance benefit as pert theory of context switching from user to kernel mode. – Chandan Srivastava May 11 '20 at 14:21
  • In a stack-limited environment (embedded programming), A_Stack probably isn't an option. On a desktop/laptop/phone, stack size isn't much of an issue. Your time is probably much better spent improving cache coherency and algorithm complexity rather than messing with memory allocations however. Unless your program is creating and destroying a LOT of A, it won't matter. – Mark Storer May 11 '20 at 14:27
  • @MarkStorer `On a desktop/laptop/phone, stack size isn't much of an issue.` Typical default stack size is about 1 to few megabytes on desktop systems. Sure that may be a lot compared to embedded, but allocate a few `A_Stack` in a recursive function, and it'll disappear fast. – eerorika May 11 '20 at 14:29
  • And **SHAME** for not having a destructor that deletes your pointers, or just using std::containers in the first place. For every new, there should be a delete. – Mark Storer May 11 '20 at 15:01
  • @eerorika My experience differs. Even though that experience spans a couple decades of C++, there are several areas I haven't worked on, so I know my experience doesn't qualify as a "statistically valid sample". I suspect no individual does. None the less, I don't recall ever running out of stack space outside infinite recurssion. YMMV (and does in eerorika's case, and I doubt they're an isolated case). Until quite recently game consoles had sharply limited stack sizes too. – Mark Storer May 11 '20 at 15:14
  • Sorry for not putting my point correctly. For allocation I will use heap only means I will call either new A_Stack or new A_Heap. My question is that which version of A will be more efficient? A_Stack, which is allocating all the data in same block or A_Heap, which is doing two more call to new? – – Chandan Srivastava May 12 '20 at 05:30
  • @MarkStorer reason for not writing the desctrutor is just to provide minimum code to put my question to ease the reader. This was not a full fledged implementation of the class. – Chandan Srivastava May 12 '20 at 05:33

1 Answers1

1

in C++, is stack allocation is more efficient ...?

Yes, in terms of time.

Typically not, in terms of stack usage, for obvious reason.

... when allocating multiple data inside a object?

Still yes.

Note that in absolute terms, the cost of allocation can be quite small. As such, whether this difference in efficiency is significant, may depend on how many allocations you are performing.

Note that A_Stack is a very large object. Only very few of them fit onto a typically sized stack, and that space is shared with all other automatic variables. Creating such object on the stack can have a high risk of causing the stack to overflow, if not handled carefully.

What you could do is allocate a single A_Stack object dynamically. This minimises the number of dynamic allocations while still not eating up all of the stack space.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I agree with allocating A_Stack dynamically. It gives you the best of both worlds. – Mark Storer May 11 '20 at 14:29
  • Sorry for not putting my point correctly. For allocation I will use heap only means I will call either new A_Stack or new A_Heap. My question is that which version of A will be more efficient? A_Stack, which is allocating all the data in same block or A_Heap, which is doing two more call to new? – Chandan Srivastava May 12 '20 at 05:29