首页 > 解决方案 > 为什么 std::vector::insert 使用 MSVC 2015 编译器比 std::copy 快 5 倍?

问题描述

我有一个将字节块复制到 std::vector 的简单函数:

std::vector<uint8_t> v;

void Write(const uint8_t * buffer, size_t count)
{
    //std::copy(buffer, buffer + count, std::back_inserter(v));

    v.insert(v.end(), buffer, buffer + count);
}

v.reserve(<buffer size>);
v.resize(0);

Write(<some buffer>, <buffer size>);

如果我使用std::vector<uint8_t>::insert它,它的工作速度比我使用std::copy.

我尝试使用启用和禁用优化的 MSVC 2015 编译此代码并得到相同的结果。

看起来有些奇怪的地方std::copystd::back_inserter实现。

标签: c++

解决方案


标准库实现在编写时考虑了性能,但只有在优化开启时才能实现性能。

//This reduces the performance dramatically if the optimization is switched off.

试图在优化关闭的情况下测量函数性能就像问自己如果宇宙中没有质量,万有引力定律是否仍然成立一样毫无意义。


推荐阅读