Minimizing the amount of malloc() calls improves performance?

前端 未结 8 907
悲&欢浪女
悲&欢浪女 2020-12-09 08:36

Consider two applications: one (num. 1) that invokes malloc() many times, and the other (num. 2) that invokes malloc() few times. Both applications allocate the same

8条回答
  •  天命终不由人
    2020-12-09 09:30

    The answer is that it depends, most of the potential slowness rather comes from malloc() and free() in combination and usually #1 and #2 will be of similar speed.

    All malloc() implementations do have an indexing mechanism, but the speed of adding a new block to the index is usually not dependant on the number of blocks already in the index.

    Most of the slowness of malloc comes from two sources

    • searching for a suitable free block among the previously freed(blocks)
    • multi-processor problems with locking

    Writing my own almost standards compliant malloc() replacement tool malloc() && free() times from 35% to 3-4%, and it seriously optimised those two factors. It would likely have been a similar speed to use some other high-performance malloc, but having our own was more portable to esoteric devices and of course allows free to be inlined in some places.

提交回复
热议问题