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

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

    Just to play devil's advocate, here's how Qt does it:

    Let's assume that we append 15000 characters to the QString string. Then the following 18 reallocations (out of a possible 15000) occur when QString runs out of space: 4, 8, 12, 16, 20, 52, 116, 244, 500, 1012, 2036, 4084, 6132, 8180, 10228, 12276, 14324, 16372. At the end, the QString has 16372 Unicode characters allocated, 15000 of which are occupied.

    The values above may seem a bit strange, but here are the guiding principles:

    QString allocates 4 characters at a time until it reaches size 20. From 20 to 4084, it advances by doubling the size each time. More precisely, it advances to the next power of two, minus 12. (Some memory allocators perform worst when requested exact powers of two, because they use a few bytes per block for book-keeping.) From 4084 on, it advances by blocks of 2048 characters (4096 bytes). This makes sense because modern operating systems don't copy the entire data when reallocating a buffer; the physical memory pages are simply reordered, and only the data on the first and last pages actually needs to be copied.

    I like the way they anticipate operating system features in code that is meant to perform well from smartphones to server farms. Given that they're smarter people than me, I'd assume that said feature is available in all modern OSes.

提交回复
热议问题