【发布时间】:2018-04-12 09:56:56
【问题描述】:
我对 C++ 向量有疑问。我在向量 (int) 类型上测试 1000000 push_back,它仅在
4 毫秒
vector <int> Test;
auto start_t = chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000; i++) Test.push_back(i);
cout << chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start_t).count() << " milliseconds\n" << endl;
但如果我制作了自己的数组引擎,即使我将分配设置为像这样分配大小(计数 * 2)(对于每个分配时间),也需要大约 3 分钟才能完成此操作
template <typename T>
class Array {
private:
T * storage_;
int alloc_ = 0;
int count_ = 0;
int all_ = 0;
public:
Array() = default;
~Array() { delete[] storage_; }
void Set(const T & __t) {
if(count_ + 1 >= alloc_) {
T * temp = new T[count_ * 2 + 4];
if(count_ > 0) for (int i = 0; i < count_; i++) temp[i] = storage_[i];
delete[] storage_;
storage_ = temp;
all_++;
}
storage_[count_++] = __t;
}
int all() { return all_; }
int count() { return count_; }
};
……这速度怎么可能?是缓存吗?因为我不相信它是一个 c++ 优化,因为在优化上做过什么,它不能像这样使向量快速......我认为它是完全缓存或其他检测我们有 1000000 次推回的东西,所以分配 1000000 大小在开始和做的过程中......是真的还是别的什么?
【问题讨论】:
-
或者什么,我会说
-
你应该考虑使用std::vector::reserve并且你需要阅读C++文档containers。顺便说一句,一些 C++ 标准库是免费软件(打包在 C++ 编译器中,如 GCC...),因此您可以研究它们的实现和源代码。
-
__t是 UB。͏͏͏͏͏͏
标签: c++ vector dynamic-memory-allocation allocation