Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dlopen vs linking overhead

Suppose I have a library - foo.so . When building my binary (which needs this library), I can either (1) link foo.so , or, (2) within the program source code, dlopen this library and then call functions provided by this library

Is there any performance difference between (1) and (2) when I call a function from the library? Note that I am aware that there will be different initialization characteristics (like the cost of the dlopen , overhead for first usage of a symbol etc) but in the steady state, are both alternatives equally fast or is one faster?

Thanks.

like image 494
MK. Avatar asked Aug 07 '13 05:08

MK.


People also ask

What does Dlopen mean?

DESCRIPTION top. dlopen() The function dlopen() loads the dynamic shared object (shared library) file named by the null-terminated string filename and returns an opaque "handle" for the loaded object.

Is Dlopen a system call?

The implementation of dlopen will call open (which is a system call) to open the library file so it can be read.

What is dynamic linking in SPCC?

Dynamic linking means that the code for some external routines is located and loaded when the program is first run. When you compile a program that uses shared libraries, the shared libraries are dynamically linked to your program by default.

How does Ld so work?

When a program linked with shared libraries runs, program execution does not immediately start with that program's first statement. Instead, the operating system loads and executes the dynamic linker (usually called ld.so), which then scans the list of library names embedded in the executable.


1 Answers

If the library is a shared object (ie some lib*.so file) compiled with gcc -Wall -fPIC -O2 and linked with gcc -shared then it is an ELF Position Independent Code shared library.

PIC is a bit more costly on 32 bits x86 -which has few registers- than on 64 bits x86-64 -which has some addressing mode facilitating PIC

It is the same (in steady state) performance wise if it is dlopen-ed or if it is dynamically linked. Because in both cases the real linking is done by the dynamic linker (e.g. ld-linux.so) sine libdl.so is basically a wrapper to the dynamic linker.

What matters performance wise when called is the code inside the lib*.so and it does not change if you dlopen it or if you link it.

Things could be slightly different if the library is statically linked lib*.a. You could even compile and link both the library and the program with the link time optimization ability of recent GCC compilers (compile and link with gcc -flto -Wall -O2)

Read Drepper's How to Write Shared Library paper and the Program Library HowTo and Levine's Linkers & Loaders book.

like image 109
Basile Starynkevitch Avatar answered Oct 04 '22 03:10

Basile Starynkevitch