std::vector の実験
std::vector を少し高速化する - ひでたそ覚書帳 の実証実験
- copy constructor のみ
- move constructor を追加
- noexcept を追加
copy constructor のみ
#include <iostream> #include <vector> struct S { /*default constructor*/ S() : id(counter++) { std::cout << "create id=" << id << std::endl; } /*copy constructor*/ S(const S& rhs) : id(counter++) { std::cout << "copy id=" << id << " from id=" << rhs.id << std::endl; } /*destructor*/ ~S() { std::cout << "delete id=" << id << std::endl; } int id; static int counter; }; int S::counter = 0; int main() { std::vector<S> v{}; std::cout << "[simple append]" << std::endl; v.push_back(S{}); std::cout << std::endl; std::cout << "[reallocate & append]" << std::endl; v.push_back(S{}); std::cout << std::endl; std::cout << "[finish]" << std::endl; return 0; }
output
[simple append] create id=0 copy id=1 from id=0 delete id=0 [reallocate & append] create id=2 copy id=3 from id=2 copy id=4 from id=1 delete id=1 delete id=2 [finish] delete id=4 delete id=3
move constructor を追加
#include <iostream> #include <vector> struct S { /*default constructor*/ S() : id(counter++) { std::cout << "create id=" << id << std::endl; } /*copy constructor*/ S(const S& rhs) : id(counter++) { std::cout << "copy id=" << id << " from id=" << rhs.id << std::endl; } /*move constructor*/ S(S&& rhs) : id(counter++) { std::cout << "move id=" << id << " from id=" << rhs.id << std::endl; } /*destructor*/ ~S() { std::cout << "delete id=" << id << std::endl; } int id; static int counter; }; int S::counter = 0; int main() { std::vector<S> v{}; std::cout << "[simple append]" << std::endl; v.push_back(S{}); std::cout << std::endl; std::cout << "[reallocate & append]" << std::endl; v.push_back(S{}); std::cout << std::endl; std::cout << "[finish]" << std::endl; return 0; }
output
[simple append] create id=0 move id=1 from id=0 delete id=0 [reallocate & append] create id=2 move id=3 from id=2 copy id=4 from id=1 delete id=1 delete id=2 [finish] delete id=4 delete id=3
noexcept を追加
#include <iostream> #include <vector> struct S { /*default constructor*/ S() : id(counter++) { std::cout << "create id=" << id << std::endl; } /*copy constructor*/ S(const S& rhs) : id(counter++) { std::cout << "copy id=" << id << " from id=" << rhs.id << std::endl; } /*move constructor*/ S(S&& rhs) noexcept : id(counter++) { std::cout << "move id=" << id << " from id=" << rhs.id << std::endl; } /*destructor*/ ~S() { std::cout << "delete id=" << id << std::endl; } int id; static int counter; }; int S::counter = 0; int main() { std::vector<S> v{}; std::cout << "[simple append]" << std::endl; v.push_back(S{}); std::cout << std::endl; std::cout << "[reallocate & append]" << std::endl; v.push_back(S{}); std::cout << std::endl; std::cout << "[finish]" << std::endl; return 0; }
output
[simple append] create id=0 move id=1 from id=0 delete id=0 [reallocate & append] create id=2 move id=3 from id=2 move id=4 from id=1 delete id=1 delete id=2 [finish] delete id=4 delete id=3