Search code examples
cmemory-managementglibtcmalloc

using tcmalloc with glib


I want to test the performance improvement that I could get by using Google's tcmalloc. My program is built using quite a lot of the utilities provided by glib (hashes, lists, arrays, ...). So what I want is basically to make glib to use tcmalloc instead of glibc's malloc.

I could address this issue with two approaches:

  1. By compiling glib with the -tcmalloc option.
  2. by using g_mem_set_vtable () from the glib's memory allocation functions.

I actually prefer the second one but I have not found any examples for implementing it.

Any hints ? Any ideas for doing this ?


Solution

  • You could use the LD_PRELOAD method suggested in the tcmalloc documentation.

    Alternatively, before using any glib functions, load the tcmalloc library using dlopen(). dlsym() the malloc(), realloc(), and free() routines, and initialize a struct GMemVTable with them. (Assuming the tcmalloc calloc() is superior, that too). Be sure to initialize members you don't use to 0 (C99 named member initialization is great for this). Lastly call g_mem_set_vtable()