Should I cache dlsym's return value?

c, dlsym, dynamic-linking, performance, posix

Solution

The `dlsym` function does not do any caching. It is simply accessing the ELF symbol tables (using its hash table, which is not very well implemented).

I think you should avoid calling `dlsym` on the same name and library a lot of times (e.g. millions of times).

You might use lazy techniques: put e.g. the name & library used in your `dlsym` calls together (in some of your structure or class) with the `dlsym`-ed function pointer, and call `dlsym` only when that pointer is null.

You also might want to catch `dlsym` failure as quickly as possible.

FWIW, you can call `dlopen` and `dlsym` a lot of times. In particular, you can have many dozens of thousands of `dlopen`-ed shared libraries on Linux, as my manydl.c example demonstrates. But avoid `dlclose`-ing a library if you still have an active call frame for some `dlsym`-ed function inside. Actually, you might never call `dlclose` and your program would still work (with a slight process address space leak).

Problem

I'm using the POSIX `dlopen`/`dlsym` API's to load dynamic libraries at runtime and then call functions from those libraries by name. Is it a good idea, performance-wise, to store the result of `dlsym` somewhere? Or does dlsym do its own caching already and would adding another layer be useless or even detrimental? Functions could potentially be called many, many times, but I don't really have a way of knowing in advance which ones, or how often they will be called. Thanks!

Original source