V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
wellhome
V2EX  ›  Go 编程语言

Golang 编译的时候,是不是把第三库所有的函数都编译进去了

  •  
  •   wellhome · 2020-12-15 21:02:33 +08:00 · 2432 次点击
    这是一个创建于 1234 天前的主题,其中的信息可能已经有所发展或是发生改变。
    引用了一个第三方包, 只用到其中一部分函数,那些没有用到的函数是不是也被编译到静态二进制文件中了?
    9 条回复    2020-12-26 23:56:34 +08:00
    lemy
        1
    lemy  
       2020-12-15 21:06:29 +08:00
    是的。而且不止 golang,很多方法都是。
    cmostuor
        2
    cmostuor  
       2020-12-15 21:07:58 +08:00
    只包含要用到的(不管系统库还是第三库) 没用到的不编译 不信反编译看看
    Liyiw
        3
    Liyiw  
       2020-12-15 21:20:22 +08:00
    上面两位究竟谁对谁错
    Vegetable
        4
    Vegetable  
       2020-12-15 21:31:25 +08:00
    不是。在 1.7 版本引入了 method pruning,没有引用和反射的方法将不会被打包。
    参见

    https://blog.golang.org/go1.7-binary-size


    The second change is method pruning. Until 1.6, all methods on all used types were kept, even if some of the methods were never called. This is because they might be called through an interface, or called dynamically using the reflect package. Now the compiler discards any unexported methods that do not match an interface. Similarly the linker can discard other exported methods, those that are only accessible through reflection, if the corresponding reflection features are not used anywhere in the program. That change shrinks binaries by 5–20%.
    icy37785
        5
    icy37785  
       2020-12-15 21:43:13 +08:00
    @Liyiw 二楼的是对的,一楼的是错的。
    Vegetable
        6
    Vegetable  
       2020-12-15 21:44:21 +08:00
    关于函数本身而不是方法。并没有明确的规范说明未使用的函数究竟会不会打包到二进制文件,不过目前验证来看也是会丢弃的,丢弃这个远比方法简单,因为 Go 中函数是不能反射的,直接丢掉就行了。
    SingeeKing
        7
    SingeeKing  
       2020-12-16 10:04:10 +08:00
    我感觉好像只有 Java 会这样,其他的「编译型」语言连 js 都有 Tree Shaking 了
    wellhome
        8
    wellhome  
    OP
       2020-12-17 18:51:04 +08:00
    那这点比 python 强阿。python 用个第三方包中的某个程序,要把整个包都装一下。
    aliipay
        9
    aliipay  
       2020-12-26 23:56:34 +08:00
    @wellhome 装了后再手动删代码也是可以的[:doge]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   910 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:08 · PVG 07:08 · LAX 16:08 · JFK 19:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.