calloc/malloc比C++中的operator new更快

adn*_*ili 0 c++ dynamic-memory-allocation

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

编辑:

我想应该已经明白我没有使用new运算符来调用构造函数.只是像数组一样的内存分配.

use*_*421 7

你在比较苹果和橘子.malloc()calloc()分配内存.new通过可能过度运算的运算符分配内存,并调用构造函数.他们做不同的事情.比较它们无效."使用C++编译器编译程序"的事实是(a)显而易见的,(b)无关紧要.

  • @adnankamili这根本不明显. (3认同)
  • 然后考虑它们是等价的情况,即对于malloc,构造函数什么都不做的情况,或者calloc是零初始化的情况.或者将它们与对操作员新功能的调用进行比较.或者更好的是将问题视为重复...... (2认同)

Jer*_*fin 6

对于大多数编译器我测试过,额外的初始化时进行使用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
Run Code Online (Sandbox Code Playgroud)

那么,malloc是平均水平,但有速度足够变化(在这两个newmalloc)是一个单独的调用new实际上可能比一个单独的调用速度更快malloc.