Which is faster: Stack allocation or Heap allocation

前端 未结 23 2005
悲&欢浪女
悲&欢浪女 2020-11-22 07:40

This question may sound fairly elementary, but this is a debate I had with another developer I work with.

I was taking care to stack allocate things where I could, i

23条回答
  •  青春惊慌失措
    2020-11-22 07:55

    As others have said, stack allocation is generally much faster.

    However, if your objects are expensive to copy, allocating on the stack may lead to an huge performance hit later when you use the objects if you aren't careful.

    For example, if you allocate something on the stack, and then put it into a container, it would have been better to allocate on the heap and store the pointer in the container (e.g. with a std::shared_ptr<>). The same thing is true if you are passing or returning objects by value, and other similar scenarios.

    The point is that although stack allocation is usually better than heap allocation in many cases, sometimes if you go out of your way to stack allocate when it doesn't best fit the model of computation, it can cause more problems than it solves.

提交回复
热议问题