c++ - 为什么 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::copy
或std::back_inserter
实现。
解决方案
标准库实现在编写时考虑了性能,但只有在优化开启时才能实现性能。
//This reduces the performance dramatically if the optimization is switched off.
试图在优化关闭的情况下测量函数性能就像问自己如果宇宙中没有质量,万有引力定律是否仍然成立一样毫无意义。
推荐阅读
- asp.net-web-api2 - Microsoft.CodeDom.Providers.DotNetCompilerPlatform(Roslyn 编译器)在 Web API 2 项目中有用吗?
- python - 如何在 C++ 中展平颜色直方图?
- javascript - Rate 组件的验证 ant.design
- php - PHP 是否可以减少类和构造函数中参数声明和初始化的重复?
- google-chrome - 测试浏览器(Firefox、Chrome、IE)和 HSTS
- r - 如何在模型保存文件中保存没有数据集的 R 模型
- tvos - 自定义子类collectionview - 调用preferredFocusEnvironments,但视图不聚焦
- javascript - Vue - 将方法作为道具传递给孩子
- python - 使用python进行光栅到点转换
- windows - 检测远程计算机重新启动并重新连接网络文件夹的脚本