清除向量或定义一个新向量,哪个更快 [英] clearing a vector or defining a new vector, which one is faster

查看:61
本文介绍了清除向量或定义一个新向量,哪个更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方法更快且开销更少?

Which method is faster and has less overhead?

方法1:

void foo() {
  std::vector< int > aVector;
  for ( int i = 0; i < 1000000; ++i ) {
     aVector.clear();
     aVector.push_back( i );
  }
}

方法2:

void foo() {
  for ( int i = 0; i < 1000000; ++i ) {
     std::vector< int > aVector;
     aVector.push_back( i );
  }
}

您可能会说该示例没有意义!但这只是我的大代码中的一小段.简而言之,我想知道

You may say that the example is meaningless! But this is just a snippet from my big code. In short I want to know is it better to

创建一个向量,然后将其清除以备使用"

"create a vector once and clear it for usage"

每次创建一个新载体"

"create a new vector every time"

更新

感谢您的建议,我对它们都进行了测试,这是结果

Thanks for the suggestions, I tested both and here are the results

方法1:

 $ time ./test1

 real    0m0.044s
 user    0m0.042s
 sys     0m0.002s

方法2:

$ time ./test2

real    0m0.601s
user    0m0.599s
sys     0m0.002s

清除向量更好.也许这对别人有帮助:)

Clearing the vector is better. Maybe this help someone else :)

推荐答案

clear()最有可能更快,因为您将保留为先前的分配的内存.将push_back()放入向量中,从而减少了分配的需要.

The clear() is most likely to be faster, as you will retain the memory that has been allocated for previous push_back()s into the vector, thus decreasing the need for allocation.

还可以消除每个循环1个构造函数调用和1个析构函数调用.

Also you do away with 1 constructor call and 1 destructor call per loop.

这全都忽略了您是编译器优化程序可能会对这段代码执行的操作.

This is all ignoring what you're compiler optimizer might do with this code.

这篇关于清除向量或定义一个新向量,哪个更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆