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!
The
dlsymfunction 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
dlsymon 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
dlsymcalls together (in some of your structure or class) with thedlsym-ed function pointer, and calldlsymonly when that pointer is null.You also might want to catch
dlsymfailure as quickly as possible.FWIW, you can call
dlopenanddlsyma lot of times. In particular, you can have many dozens of thousands ofdlopen-ed shared libraries on Linux, as my manydl.c example demonstrates. But avoiddlclose-ing a library if you still have an active call frame for somedlsym-ed function inside. Actually, you might never calldlcloseand your program would still work (with a slight process address space leak).