Golang 对具有静态内容的地图定义的行为(编译时构造?)

Golang behaviour on map definition with static content (compile time construction?)

让我们采用以下 Golang 表达式:

type MyStruct struct {
  foo int,
  bar map[string]MyInterface 
}
type MyInterface interface { /* ... */ }
func firstFunc() { /* ...*/ }
func secondFunc() { /* ...*/ }

使用以下生成器函数:

func NewMyStruct() *MyStruct {
  // Building a map made of only static content, known at compile time
  // Assigning it to a local variable
  m := map[string]MyInterface {
    "first": firstFunc,
    "second": secondFunc,
  }
  /* ... */
  return &MyStruct{
    bar: m, // Copying the map into the struct field
    /* ... */
  }
}

我看到这段代码并决定尝试在内存管理方面优化它 and/or 执行时间。 来自 C++ 世界,我习惯了“静态与动态分配”的困境和 constexpr 的使用。我试图在 Golang 中实现相同的目标:避免 constructing/allocating 在语言允许的范围内过于频繁地使用数据结构。

问题1:在NewMyStruct()中,临时地图有效分配给mconstructed/allocated 每次通话?

问题2: 编译器能否检测到临时映射是由静态内容构成的,并一次性构造好?

我的另一个解决方案是寻找一个全局定义的映射并使用指针从 MyStruct 个实例中引用它。

因为, this is almost certainly premature optimization. However, if you've already found that this has some significant time cost in your program and are just looking for options, this Playground link显示了一种在程序启动时构建地图并共享它的方法。本质就是:

return &MyStruct{bar: sharedMap, /*...*/}

此时需要创建共享地图。如果无法使用简单的静态初始化,请使用 an init function,或添加 sync.Once 以便在第一次调用 New 函数时仅构造一次映射。