I have tried to allocate space for 10^7 integers in heap and stack memory to see which one is faster. Obviously allocating in heap-memory was much faster but I don't understand the reason.
#include <bits/stdc++.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
int main()
{
high_resolution_clock::time_point t1 = high_resolution_clock::now();
int *p = new int[1e7];
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << duration / 1e6 << "\n"; // 5e-06
t1 = high_resolution_clock::now();
vector<int> v(1e7);
t2 = high_resolution_clock::now();
duration = duration_cast<microseconds>( t2 - t1 ).count();
cout << duration / 1e6 << "\n"; // 0.112284
return 0;
}
new int[1e7]
allocates space for 1e7 int
values and doesn't initialize them.
vector<int> v(1e7);
creates a vector<int>
object on the stack, and the constructor for that object allocates space for 1e7 int
values on the heap. It also initializes each int
value to 0.
The difference in speed is because of the initialization.
To compare the speed of stack allocation you need to allocate an array on the stack:
int data[1e7];
but be warned: there's a good chance that this will fail because the stack isn't large enough for that big an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With