为什么泄漏内存比在动态数组上执行 delete[] 慢
Why leaking memory is slower than doing delete[] on the dynamic array
我刚刚开始使用谷歌基准测试进行微基准测试,我得到了我无法真正解释的结果。我有一个函数URLify(编码空格的基本函数(。我将字符串转换为 char * 并将其传递给函数
这就是我使用谷歌基准测试和完全优化来测试它的方式。 使用 VS 2015 x64
while (state.KeepRunning()) {
char* ch = new char[str.length()*2 ]; //str is a string I want to encode
memcpy(ch, &str[0], str.length() + 1);
URLify(ch, str.length());
delete[] ch;
}
这是进行 30000 次迭代和 5 次重复的结果
BenchURLify/iterations:30000/repeats:5 5370 ns 5729 ns 30000
BenchURLify/iterations:30000/repeats:5 5366 ns 5208 ns 30000
BenchURLify/iterations:30000/repeats:5 5349 ns 5208 ns 30000
BenchURLify/iterations:30000/repeats:5 5364 ns 5729 ns 30000
BenchURLify/iterations:30000/repeats:5 5356 ns 5208 ns 30000
BenchURLify/iterations:30000/repeats:5_mean 5361 ns 5417 ns 5
BenchURLify/iterations:30000/repeats:5_median 5364 ns 5208 ns 5
BenchURLify/iterations:30000/repeats:5_stddev 8.48 ns 285 ns 5
但是当我从代码中删除 delete[] 时,谷歌基准测试显示了不同的结果,而不是我预期的结果。我认为每次迭代释放内存比泄漏内存慢。但这是没有删除[] ch的结果
BenchURLify/iterations:30000/repeats:5 7240 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7245 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7116 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7091 ns 7292 ns 30000
BenchURLify/iterations:30000/repeats:5 7116 ns 6771 ns 30000
BenchURLify/iterations:30000/repeats:5_mean 7162 ns 7188 ns 5
BenchURLify/iterations:30000/repeats:5_median 7116 ns 7292 ns 5
BenchURLify/iterations:30000/repeats:5_stddev 74.6 ns 233 ns 5
所以我的问题是为什么做 delete[] 比泄漏内存显示出更好的性能?或者我在这里错过了什么
delete[] 函数的作用很少,而且速度非常快。系统可能会在每次迭代中继续返回相同的内存,并且可以在用户空间中完成(在malloc期间内核中会发生什么?有更多的细节(。
内存以块的形式分配给进程。 如果让内存泄漏,则在某些时候需要使用内核调用来扩展内存空间。这些内核调用可能比删除调用昂贵得多。
有很多可能性。
- 测试是有缺陷的,时间并不代表你的想法。
- 释放内存后,运行时每次都可以为您分配相同的块。但是,当不释放内存时,运行时必须分配一个新块,这可能需要一些时间,并且可能必须从操作系统分配更多内存(取决于内存分配在特定环境中的工作方式(。
- 更多。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 运算符C++ "delete []"仅删除 2 个前值
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- 继承类上的运算符new和delete.操作员删除未执行
- Sqlite3/C++在不更改数据库大小的情况下执行DELETE语句
- 是否可以对全局运算符“new”和“delete”执行回调
- 执行"delete this"时缺少虚拟析构函数
- c++,最快的STL容器,用于递归地执行{delete[begin], insert[end]和对整个数组内容求和}
- 如果在成员函数中执行"delete this;",会发生什么情况?
- 当delete my_object;执行?是否所有其他内存都被sizeof(MyClass)向左移动