gpt4 book ai didi

c++ - calloc/malloc 比 C++ 中的 operator new 快吗

转载 作者:太空宇宙 更新时间:2023-11-04 14:35:33 28 4
gpt4 key购买 nike

我想知道的是,如果我在 C++ 程序中使用 calloc/malloc 而不是 operator new,它会使内存分配更快,还是因为使用 C++ 编译器来编译程序,这无关紧要。

编辑:

我想很明显我没有使用 new 运算符来调用构造函数。只是像数组一样的内存分配。

最佳答案

对于我测试过的大多数编译器,当您使用 new 时执行的额外初始化意味着它比 malloc分钟(在至少在处理两者至少具有模糊可比性的简单类型时)。例如:

Test Name:   D000001                         Class Name:  Allocation
CPU Time: 56.8 nanoseconds plus or minus 2.84
Wall/CPU: 1.02 ratio. Iteration Count: 419430400
Test Description:
Dynamic array allocation, use and deallocation time measurement
Dynamic array of 1000 integers
get space on heap using malloc() and use it in a procedure on each call



Test Name: D000002 Class Name: Allocation
CPU Time: 238 nanoseconds plus or minus 11.9
Wall/CPU: 1.03 ratio. Iteration Count: 104857600
Test Description:
Dynamic array allocation, initialization, use and deallocation time measurement

Dynamic array of 1000 integers
get space on heap using malloc() and use it in a procedure on each call



Test Name: D000003 Class Name: Allocation
CPU Time: 60.4 nanoseconds plus or minus 3.02
Wall/CPU: 1.02 ratio. Iteration Count: 419430400
Test Description:
Dynamic array allocation, use and deallocation time measurement
Dynamic array of 1000 integers
get space on heap using NEW and use it in a procedure on each call



Test Name: D000004 Class Name: Allocation
CPU Time: 249 nanoseconds plus or minus 12.4
Wall/CPU: 1.03 ratio. Iteration Count: 104857600
Test Description:
Dynamic array allocation, initialization, use and deallocation time measurement

Dynamic array of 1000 integers
get space on heap using NEW and use it in a procedure on each call

因此,malloc 的平均速度更快,但在速度上有足够的差异(在 newmalloc 中),单个调用new 实际上可能比单独调用 malloc 更快。​​

关于c++ - calloc/malloc 比 C++ 中的 operator new 快吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23591196/

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