Witam,
robię trochę testów szybkości działania dla poniższego kodu. W jaki sposób prawidłowo uniknąć kopiowania obiektu przy dodawaniu go do vectora ? Dopiero rozgryzam zasadę działania r-value reference
class Test
{
public:
Test() : _a(0), _str("")
{
//std::cout << "empty constructor\n";
}
Test(const int &a, const std::string &str) : _a(a), _str(str)
{
//std::cout << "constructor parametrised with int a = " << a << std::endl;
}
const Test(const Test &other)
{
_a = other._a;
_str = other._str;
//std::cout << "copy constructor\n";
}
Test(Test &&other): _a(other._a), _str(other._str)
{
//std::cout << "move constructor\n";
}
const Test &operator=(const Test &other)
{
//std::cout << "assignment operator\n";
this->_a = other._a;
return *this;
}
~Test()
{
//std::cout << "destructor running\n";
}
private:
int _a;
std::string _str;
};
int main()
{
int kIterations = 500000;
std::string kString = "jakis tekst do powielania";
std::vector<Test> vec;
std::vector<std::unique_ptr<Test>> vPtrs;
auto start = std::chrono::steady_clock::now();
for (int i = 0; i < kIterations; i++)
{
vPtrs.push_back(std::make_unique<Test>(i, kString));
}
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::steady_clock::now() - start);
std::cout << "make_unique: " << duration.count() << " ms\n";
start = std::chrono::steady_clock::now();
for (int i = 0; i < kIterations; i++)
{
vec.push_back({ i, kString });
}
duration = std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::steady_clock::now() - start);
std::cout << "copy constructor: " << duration.count() << " ms\n";
start = std::chrono::steady_clock::now();
for (int i = 0; i < kIterations; i++)
{
vec.push_back(std::move(Test(i, kString)));
}
duration = std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::steady_clock::now() - start);
std::cout << "move + copy: " << duration.count() << " ms\n";
return 0;
}
oczywiście std::move rzutuje tylko dodawany obiekt na rvalue, reszta jest kopiowana
flaga /O2
wyniki to:
make_unique: 563 ms
copy constructor: 2331 ms
move + copy: 1357 ms