views:

16

answers:

1

When implementing an elementary data structure like stack, queues, linked list et al. should I create a resource pool(of nodes) by dynamically allocating memory in bunch or should I allocate memory separately every time I need a node?

A: 

This entirely depends on your goals. By default (i.e. unless you really need to do otherwise), just do a normal allocation for each next node.

Memory pools as compared to just allocating nodes:

  • Make allocation faster. Depending on underlying allocation mechanism, sometimes significantly faster.

  • Usually less memory fragmentation, though this may not be a problem with some allocators.

  • Major drawback: waste memory on reserved, but not used nodes. This is very important if you use data structure indiscriminately (e.g. 1000s of instances) as opposed to just having a couple of instances.

Because of the drawback, memory pools are not suitable for generic situations.

In C++ all standard containers have an allocator template parameter.

doublep