Go接口优化

3
关于Russ Cox在2009年12月发表的文章《Go数据结构:接口》(链接:https://research.swtch.com/interfaces),在内存优化部分,Russ提到如果存储在interface{}中的数据比uintptr的大小还要小,那么该值将直接存储在接口中,不需要分配数据并获取其地址。如果使用以下代码进行测试:-
package main

import (
    "fmt"
    "unsafe"
)

type iface struct {
    _    unsafe.Pointer
    data unsafe.Pointer
}

func main() {
    var i interface{} = 12
    var pi = (*iface)(unsafe.Pointer(&i))
    fmt.Printf("if.data: %p", pi.data)
}

结果是:-
if.data: 0x127e2c

很明显这是一个地址,而不是优化后期望的值12。

Go语言不再支持接口优化了吗?还是我的理解有误?


接口的实现是编译器内部的事情,甚至在gc和gcc之间可能会有所不同。另外:您的测试代码依赖于实现细节。 - Volker
1
参见:https://github.com/golang/go/issues/12128 - user142162
有一条评论是由PeterSO发表的,我点击了上箭头表示它添加了一些有用的内容,但是PeterSO的评论已经消失了。不知道为什么会这样。 - collymy
@collymy:我把我的评论转换成了一个答案。 - peterSO
1个回答

1

Compiler And Runtime Optimizations

This page lists optimizations done by the compilers. Note that these are not guaranteed by the language specification.

Interface values

Word-sized value in an interface value

Putting a word-sized-or-less non-pointer type in an interface value doesn't allocate.

gc: 1.0-1.3, but not in 1.4+
gccgo: never

Go语言从Go1.4版本开始不再进行该优化。


1
对于好奇的人,这是为了使GC与其余正在运行的代码并发。特别是请参见此问题此提交 - kostix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接