Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL vector performance

Tags:

c++

vector

STL vector class stores a copy of the object using copy constructor each time I call push_back. Wouldn't it slow down the program? I can have a custom linkedlist kind of class which deals with pointers to objects. Though it would not have some benefits of STL but still should be faster.

See this code below:

#include <vector>
#include <iostream>  
#include <cstring>

using namespace std;

class myclass
{
    public:
        char* text;

        myclass(const char* val)
        {
           text = new char[10]; 
           strcpy(text, val);
        }

        myclass(const myclass& v)
        {
            cout << "copy\n";
            //copy data
        }
};

int main()
{
    vector<myclass> list;
    myclass m1("first");
    myclass m2("second");

    cout << "adding first...";
    list.push_back(m1);

    cout << "adding second...";
    list.push_back(m2);

    cout << "returning...";
    myclass& ret1 = list.at(0);
    cout << ret1.text << endl;

    return 0;
}

its output comes out as:

adding first...copy
adding second...copy
copy

The output shows the copy constructor is called both times when adding and when retrieving the value even then. Does it have any effect on performance esp when we have larger objects?

like image 299
Jeet Avatar asked Nov 29 '22 11:11

Jeet


1 Answers

Copying will affect performance. If you keep large objects in standard containers it will be a good idea to use smart pointers instead of objects itself.

like image 104
Kirill V. Lyadvinsky Avatar answered Dec 15 '22 05:12

Kirill V. Lyadvinsky