C/C++ performance of static arrays vs dynamic arrays

前端 未结 5 1321
难免孤独
难免孤独 2021-01-30 14:33

When performance is essential to an application, should consideration be given whether to declare an array on the stack vs the heap? Allow me to outline why this question has co

5条回答
  •  攒了一身酷
    2021-01-30 15:10

    Often there is a trade off between memory consumption and speed. Empirically, I have witnessed that creating array on stack is faster than allocation on heap. As the array size increases this becomes more apparent.

    You can always decrease the memory consumption. For example you can use short or char instead of int etc.

    As the array size increases, especially with the use of realloc, there might be a lot more page replacement (up and down) to maintain the contiguous location of items.

    You should also consider that there is a lower limit for the size of the things you can store in stack, for heap this limit is higher but as I told with the cost of performance.

提交回复
热议问题