简体   繁体   中英

Is it beneficial to make library functions templated to avoid compiler instructions?

Let's say I'm creating my own library in namespace l . Would it be beneficial to make as much as possible members of the namespace templated? This would encourage the compiler to only generate instructions for members that are actually called by the user of the library. To make my point clear, I'll demonstrate it here:

1)

namespace l{
    template <typename = void>
    int f() { return 3; }
}

vs.

2)

namespace l{
    int f() { return 3; }
}

It is not being called in main to show the difference.

int main() { return EXIT_SUCCESS; }

function 1) does not require additional instructions for l::f() :

main:
    push    rbp
    mov     rbp, rsp
    mov     dword ptr [rbp - 4], 0
    mov     eax, 0
    pop     rbp
    ret

function 2) does require additional instructions for l::f() ( If, again, l::f() is not called):

l::f()
    push    rbp
    mov     rbp, rsp
    mov     eax, 3
    pop     rbp
    ret
main:                                  
    push    rbp
    mov     rbp, rsp
    mov     dword ptr [rbp - 4], 0
    mov     eax, 0
    pop     rbp
    ret

tl;dr

Is it beneficial to make library functions templated to avoid compiler instructions?

No. Emitting dead code isn't the expensive part of compiling. File access, parsing and optimization (not necessarily in that order) take time, and this idea forces library clients to read & parse more code than in the regular header + library model.

Templates are usually blamed for slowing builds, not speeding them up.


It also means you can't build your library ahead of time, so each user needs to compile whichever parts they use from scratch, in every translation unit where they're used.

The total time spent compiling will probably be greater with the templated version. You'd have to profile to be sure (and I suspect this f is so small as to be immeasurable either way) but I have a hard time seeing this as a useful improvement.

Your comparison isn't representative anyway - a good compiler will discard dead code at link time. Some will also be able to inline code from static libraries, so there's no reliable effect on either compile-time or runtime performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM