Is malloc faster when I freed memory before

こ雲淡風輕ζ 提交于 2020-01-04 02:09:09

问题


When I allocate and free memory and afterwards I allocate memory that is max the size as the previously freed part.

May the 2nd allocation be faster than the first?

Maybe because it already knows a memory region that is free? Or because this part of the heap is still assigned to the process? Are there other possible advantages?

Or does it generally make no difference?

Edit: As asked in the comments:

  • I am especially interested in gcc and MSVC.
  • My assumption was that the memory was not "redeemed" by the OS before.

As there is a lot going about specific details about implementation, I'd like to make it more clear, that this is a hypothetical question. I don't intend to abuse this, but I just want to know IF this may occur and what the reasons for the hypothetical speedup might be.


回答1:


On some common platforms like GCC x86_64, there are two kinds of malloc(): the traditional kind for small allocations, and the mmap kind for large ones. Large, mmap-based allocations will have less interdependence. But traditional small ones will indeed experience a big speedup in some cases when memory has previously been free()'d.

This is because as you suggest, free() does not instantly return memory to the OS. Indeed it cannot do so in general, because the memory might be in the middle of the heap which is contiguous. So on lots of systems (but not all), malloc() will only be slow when it needs to ask the OS for more heap space.




回答2:


Memory allocation with malloc should be faster whenever you avoid making system calls like sbrk or mmap. You will at least save a context switch.

Make an experiment with the following program

#include <stdlib.h>

int main() {

    void* x = malloc(1024*1024);
    free(x);
    x = malloc(1024*1024);

}

and run it with command strace ./a.out

When you remove call to free you will notice two additional system calls brk.




回答3:


Here's simple banchmark I compiled at -O1:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv){
    for(int i=0;i<10000000;i++){
        char  volatile * p = malloc(100);
        if(!p) { perror(0); exit(1); }
        *p='x';
        //free((char*)p);
    }

    return 0;
}

An iteration cost about 60ns with free and about 150ns without on my Linux. Yes, mallocs after free can be significantly faster.

It depends on the allocated sizes. These small sizes will not be returned to the OS. For larger sizes that are powers of two, the glibc malloc starts mmaping and unmmapping and then I'd expect a slowdown in the freeing variant.



来源:https://stackoverflow.com/questions/41869662/is-malloc-faster-when-i-freed-memory-before

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!