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

后端 未结 11 1024
执笔经年
执笔经年 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: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.

提交回复
热议问题