I'm testing performance difference between pushing back Objects vs pushing back object Pointers to Vector in C++.
I've read in Stackoverflow and other articles that you should avoid pushing back pointers unless you must do so...
However, I realized that there is a HUGE performance gain for pushing back Pointers,,,
This is a simple test I ran:
tstart = chrono::system_clock::now();
vector<MyObject> VectorOfObjects;
for (int i=0; i<10000; i++) {
MyObject x("test");
VectorOfObjects.push_back(x);
}
tend = chrono::system_clock::now();
tt = tend-tstart;
cout << "Pushback Object: " << tt.count()*1000 << " Milliseconds\n" << endl;
tstart = chrono::system_clock::now();
vector<MyObject *> VectorOfPointers;
for (int i=0; i<10000; i++) {
VectorOfPointers.push_back(new MyObject("test"));
}
tend = chrono::system_clock::now();
tt = tend-tstart;
cout << "Pushback Pointers: " << tt.count()*1000 << " Milliseconds\n" << endl;
The result is actually pretty surprising:
Pushback Objects: 989 Milliseconds
Pushback Pointers: 280 Milliseconds
As you can see, pushing back pointers is 3~4 times faster than pushing back objects! which is a huge performance difference, especially when dealing with large volume of data.
So my question is: WHY NOT USE Vector of Pointers??
Answers to almost every post on Stackoverflow regarding similar question says Avoid Vector of Pointers..
I know memory leakage might be a problem,, but we can always use Smart Pointers,, and even manually deleting the pointers at destruction is not that difficult..
I'm also curious about the cause of this performance difference..
Thanks
UPDATE:
Actually I tested on ideone .... and here, pushback objects is Faster!!!
In Visual Studio,, pushing back Objects was Wayyy slower..
Why is this...??