简体   繁体   English

使库函数模板化以避免编译器指令是否有益?

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

Let's say I'm creating my own library in namespace l .假设我正在名称空间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) 1)

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

vs.对比

2) 2)

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

It is not being called in main to show the difference.没有在 main 中调用它来显示差异。

int main() { return EXIT_SUCCESS; }

function 1) does not require additional instructions for l::f() :函数 1) 不需要额外的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):函数 2) 确实需要额外的l::f()指令(如果再次未调用l::f() ):

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 tl;博士

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.您必须进行概要分析才能确定(我怀疑这个f太小以至于无法测量),但我很难将其视为有用的改进。

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.有些还能够内联静态库中的代码,因此对编译时或运行时性能没有可靠的影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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