6.3w+
社区成员
#include <iostream>
#include <vector>
#include <map>
#include <list>
#include <ctime>
using namespace std;
const static int max = 100000;
class FooVector {
public:
FooVector(initializer_list<string> l)
{
auto it = l.begin();
for (int i=0;i<l.size();++i,++it)
{
v.push_back(*it);
}
}
FooVector(vector<string> w) {
v = w;
}
private:
vector<string> v;
};
void test01()
{
vector<int> vec;
clock_t startTime = clock();
for (int i = 0; i < max; i++)
{
FooVector t{ "123","123213","12332" };
}
clock_t endTime = clock();
cout << "vector-initializer_list The test01 time is: " << (double)(endTime - startTime) << "ms" << endl;
}
void test02()
{
vector<int> vec;
clock_t startTime = clock();
vector<string> l{ "123","123213","12332" };
for (int i = 0; i < max; i++)
{
FooVector t(l);
}
clock_t endTime = clock();
cout << "vector-vector The test02 time is: " << (double)(endTime - startTime) << "ms" << endl << endl;
}
class FooMap
{
std::map<int, int> content_;
using pair_t = std::map<int, int>::value_type;
public:
FooMap(std::initializer_list<pair_t> list)
{
for (auto it = list.begin(); it != list.end(); ++it)
{
content_.insert(*it);
}
}
FooMap(std::map<int, int> m) { content_ = m; }
};
void test03()
{
clock_t startTime = clock();
for (int i = 0; i < max; i++)
{
FooMap t = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
}
clock_t endTime = clock();
cout << "map-initializer_list The test03 time is: " << (double)(endTime - startTime) << "ms" << endl;
}
void test04()
{
clock_t startTime = clock();
std::map<int, int> q;
q[1] = 2;
q[3] = 4;
q[5] = 6;
for (int i = 0; i < max; i++)
{
FooMap t(q);
}
clock_t endTime = clock();
cout << "map-map The test04 time is: " << (double)(endTime - startTime) << "ms" << endl << endl;
}
class FooList
{
std::list<string> ls;
public:
FooList(std::initializer_list<string> list)
{
for (auto it = list.begin(); it != list.end(); ++it)
{
ls.push_back(*it);
}
}
FooList(std::list<string> l) { ls = l; }
};
void test05()
{
vector<int> vec;
clock_t startTime = clock();
for (int i = 0; i < max; i++)
{
FooList t= { "wqeersf","ewewew","qwe" };
}
clock_t endTime = clock();
cout << "list-initializer_list The test05 time is: " << (double)(endTime - startTime) << "ms" << endl;
}
void test06()
{
vector<int> vec;
clock_t startTime = clock();
std::list<string> l;
l.push_back("wqeersf");
l.push_back("ewewew");
l.push_back("qwe");
for (int i = 0; i < max; i++)
{
FooList t(l);
}
clock_t endTime = clock();
cout << "list-list The test06 time is: " << (double)(endTime - startTime) << "ms" << endl << endl;
}
int main()
{
test01();
test02();
test03();
test04();
test05();
test06();
return 0;
}
很有意思的一个现象。代码没用end,是因为end比size慢,其实本质不是标题说的那样initializer_list不快,本质是initializer_list如果我们仅仅传递参数,里面不做任何事,initializer_list肯定是最快的,因为用vector对象传递参数,会调用vector的拷贝构造,然后函数体再调用赋值运算符。这里的问题其实是为什么vector直接赋值会比push_back快,不确定vector的源码中的赋值运算符怎么实现的。
我简单查了下,vector中能够赋值的操作。swap > copy > assign > 直接赋值 > push_back赋值
看对应汇编指令