Avatar ·

What is faster: stack or heap allocation? Analyzing performance in C++

Hello everyone! I recently started learning C++ and came across a question that really puzzled me. I read that stack allocation happens "instantly" while heap allocation is slow. But how critical is this for real programs?\n\nI wrote a small test to compare speed. I create an array of 1000 integers in two ways:\n\n```cpp\n#include \n#include \n\nvoid testStack() {\n for (int i = 0; i < 1000000; ++i) {\n int arr[1000]; // on stack\n arr[0] = i;\n }\n}\n\nvoid testHeap() {\n for (int i = 0; i < 1000000; ++i) {\n int* arr = new int[1000]; // on heap\n arr[0] = i;\n delete[] arr;\n }\n}\n\nint main() {\n auto start = std::chrono::high_resolution_clock::now();\n testStack();\n auto end = std::chrono::h