2024年8月6日:
向list里面循环添加数据,两种写法
for(;;){
myList.resize(myList.size()+1);
MyObject &obj= *myList.rbegin();
obj.a= itervalue;
}
第二种写法是push_back:
for(;;){
MyObject obj;
obj.a= itervalue;
myList.push_back(obj);
}
用第一种用法,是避免了push_back的拷贝构造函数,用的缺省构造函数,对于COPY构造函数效率毕竟低的场景,也许有效。但是大部分时间应该没有啥用。
效率上,找了一个评测网站:
代码:
#include <vector>
#include <list>
constexpr size_t loopCount = 1000;
struct BigObject{
double LongDouble[10000];
};
static void VectorPushBack(benchmark::State& state) {
for (auto _ : state) {
std::vector<BigObject> vec;
for (int i = 0; i < loopCount; i++) {
BigObject bo;
vec.push_back(bo);
}
benchmark::DoNotOptimize(vec);
}
}
BENCHMARK(VectorPushBack);
static void VectorEmplaceBack(benchmark::State& state) {
for (auto _ : state) {
std::vector<BigObject> vec;
for (int i = 0; i < loopCount; i++) {
vec.emplace_back();
}
benchmark::DoNotOptimize(vec);
}
}
BENCHMARK(VectorEmplaceBack);
static void ListPushBack(benchmark::State& state) {
for (auto _ : state) {
std::list<BigObject> list;
for (int i = 0; i < loopCount; i++) {
BigObject bo;
list.push_back(bo);
}
benchmark::DoNotOptimize(list);
}
}
BENCHMARK(ListPushBack);
static void ListEmplaceBack(benchmark::State& state) {
for (auto _ : state) {
std::list<BigObject> list;
for (int i = 0; i < loopCount; i++) {
list.emplace_back();
}
benchmark::DoNotOptimize(list);
}
}
BENCHMARK(ListEmplaceBack);
static void ListResize(benchmark::State& state) {
for (auto _ : state) {
std::list<BigObject> list;
for (int i = 0; i < loopCount; i++) {
BigObject bo;
//list.push_back(bo);
list.resize(list.size()+1);
BigObject &obj = *list.rbegin();
obj=bo;
}
benchmark::DoNotOptimize(list);
}
}
BENCHMARK(ListResize);
结果:push_back效率最高,高的原因不详
参考: