gpt4 book ai didi

c++ - 什么更快 : recreate or clear()?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:16 59 4
gpt4 key购买 nike

我对 C++ 中 std::vector<> 的性能有疑问。通过调用其 clear() 方法重用相同的 vector 会更快,还是重新创建 vector 会更快?

下面的例子不是真实的代码,只是为了弄清楚问题是什么:

//Example ONE: is this faster
std::vector<int> foo;
for(int i = 0; i < 100; ++i)
{
foo.clear();
for(int j = 0; j < 100; ++j)
{
foo.push_back(i+j);
}
}

//Example TWO: or is that faster?
for(int i = 0; i < 100; ++i)
{
std::vector<int> foo;
for(int j = 0; j < 100; ++j)
{
foo.push_back(i+j);
}
}

最佳答案

clear() 不能根据其契约(Contract)解除分配 vector 内存,而只是将内部“大小”标志设置为 0,因此这种方法会更快。

关于c++ - 什么更快 : recreate or clear()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7351143/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com