Is it better to allocate memory in the power of two?

后端 未结 11 1011
执笔经年
执笔经年 2020-12-08 04:26

When we use malloc() to allocate memory, should we give the size which is in power of two? Or we just give the exact size that we need?
Like



        
相关标签:
11条回答
  • 2020-12-08 04:44

    It might have been true once, but it's certainly not better.

    Just allocate the memory you need, when you need it and free it up as soon as you've finished.

    There are far too many programs that are profligate with resources - don't make yours one of them.

    0 讨论(0)
  • 2020-12-08 04:49

    You may want to allocate memory in terms of the processor's word size; not any old power of 2 will do.

    If the processor has a 32-bit word (4 bytes), then allocate in units of 4 bytes. Allocating in terms of 2 bytes may not be helpful since the processor prefers data to start on a 4 byte boundary.

    On the other hand, this may be a micro-optimization. Most memory allocation libraries are set up to return memory that is aligned at the correct position and will leave the least amount of fragmentation. If you allocate 15 bytes, the library may pad out and allocate 16 bytes. Some memory allocators have different pools based on the allocation size.

    In summary, allocate the amount of memory that you need. Let the allocation library / manager handle the actual amount for you. Put more energy into correctness and robustness than worry about these trivial issues.

    0 讨论(0)
  • 2020-12-08 04:50

    There is always testing...

    You can try a "sample" program that allocates memory in a loop. This way you can see if your compiler magically allocates memory in powers of 2. With that information, you can try to allocate the same amount of total memory using the 2 strategies: random sized blocks and power of 2 sized blocks.

    I would only expect differences, if any, for large amounts of memory though.

    0 讨论(0)
  • 2020-12-08 04:51

    With today's amount of memory and its speed I don't think it's relevant anymore.

    Furthermore, if you're gonna allocate memory frequently you better consider custom memory pooling / pre-allocation.

    0 讨论(0)
  • 2020-12-08 04:52

    You should use realloc() instead of malloc() when reallocating. http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/

    Always use a power of two? It depends on what your program is doing. If you need to reprocess your whole data structure when it grows to a power of two, yeah it makes sense. Otherwise, just allocate what you need and don't hog memory.

    0 讨论(0)
提交回复
热议问题