Go 1.9中值得关注的几个变化

liang952 1年前
   <p><a href="/misc/goto?guid=4959640874170259948">Go语言</a>在2016年当选<a href="/misc/goto?guid=4959009541261159254" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://www.tiobe.com']);">tiobe index</a>的年度编程语言。</p>    <p><img alt="Go 1.9中值得关注的几个变化" src="https://simg.open-open.com/show/53fcb7af12ccbf06f47004c20b89ac70.png"></p>    <p>转眼间6个月过去了,Go在tiobe index排行榜上继续强势攀升,在最新公布的TIBOE INDEX 7月份的排行榜上,Go挺进Top10:</p>    <p><img alt="Go 1.9中值得关注的几个变化" src="https://simg.open-open.com/show/ab00d650c757b61c3612e6e5cca1b84d.png"></p>    <p>还有不到一个月,<a href="/misc/goto?guid=4959754600549516294" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://tip.golang.org']);">Go 1.9版本</a>也要正式Release了(计划8月份发布),当前Go 1.9的最新版本是<a href="/misc/goto?guid=4959754600641029795" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">go1.9beta2</a>,本篇的实验环境也是基于该版本的,估计与final go 1.9版本不会有太大差异了。在今年的<a href="/misc/goto?guid=4959754600711859114">GopherChina大会</a>上,我曾提到:<a href="/misc/goto?guid=4959754600803934841">Go已经演进到1.9,接下来是Go 1.10还是Go 2</a>? 现在答案已经揭晓:<a href="/misc/goto?guid=4959754600905560098" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://groups.google.com']);">Go 1.10</a>。估计Go core team认为Go 1还有很多待改善和优化的地方,或者说Go2的大改时机依旧未到。Go team的tech lead <a href="/misc/goto?guid=4959754601000656549" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://swtch.com']);">Russ Cox</a>将在今年的<a href="/misc/goto?guid=4959754601104947890" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://www.gophercon.com']);">GopherCon大会</a>上做一个题为”The Future of Go”的主题演讲,期待从<a href="/misc/goto?guid=4959754601191839197" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://pdos.csail.mit.edu']);">Russ</a>的口中能够得到一些关于Go未来的信息。</p>    <p>言归正传,我们还是来看看Go 1.9究竟有哪些值得我们关注的变化,虽然我个人觉得Go1.9的变动的幅度并不是很大^0^。</p>    <h2>一、Type alias</h2>    <p>Go 1.9依然属于Go1系,因此继续遵守<a href="/misc/goto?guid=4959009844027315378" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://golang.org']);">Go1兼容性承诺</a>。这一点在我的<a href="/misc/goto?guid=4959640874170259948">“值得关注的几个变化”系列文章</a>中几乎每次都要提到。</p>    <p>不过Go 1.9在语言语法层面上新增了一个“<a href="/misc/goto?guid=4959750046427207134" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">颇具争议</a>”的语法: <a href="/misc/goto?guid=4959010500283407136" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://golang.org']);">Type Alias</a>。关于type alias的<a href="/misc/goto?guid=4959750046427207134" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">proposal</a>最初由Go语言之父之一的<a href="/misc/goto?guid=4959754601385668300" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">Robert Griesemer</a>提出,并计划于<a href="/misc/goto?guid=4959754601475774362">Go 1.8</a>加入Go语言。但由于Go 1.8的type alias实现过于匆忙,测试不够充分,在临近Go 1.8发布的时候发现了无法短时间解决的问题,因此Go team决定将type alias的实现<a href="/misc/goto?guid=4959754601562134978" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">从Go 1.8中回退</a>。</p>    <p>Go 1.9 dev cycle伊始,type alias就重新被纳入。这次Russ Cox亲自撰写文章<a href="/misc/goto?guid=4959010500378983721" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://talks.golang.org']);">《Codebase Refactoring (with help from Go)》</a>为type alias的加入做铺垫,并开启<a href="/misc/goto?guid=4959750046525728824" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">新的discussion</a>对之前Go 1.8的general alias语法形式做进一步优化,最终1.9仅仅选择了<a href="/misc/goto?guid=4959010500283407136" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://golang.org']);">type alias</a>,而不需要像Go 1.8中general alias那样引入新的操作符(=>)。这样,结合Go已实现的interchangeable constant、function、variable,外加type alias,Go终于在语言层面实现了对“Gradual code repair(渐进式代码重构)”理念的初步支持。</p>    <blockquote>     <p>注:由于type alias的加入,在做Go 1.9相关的代码试验之前,最好先升级一下你本地编辑器/IDE插件(比如:<a href="/misc/goto?guid=4959754601710202671">vim-go</a>、<a href="/misc/goto?guid=4959754601795703327">vscode-go</a>)以及各种<a href="/misc/goto?guid=4959754601884392198">tools</a>的版本。</p>    </blockquote>    <p>官方对type alias的定义非常简单:</p>    <blockquote>     <p>An alias declaration binds an identifier to the given type.</p>    </blockquote>    <p>我们怎么来理解新增的type alias和传统的type definition的区别呢?</p>    <pre>  <code class="language-go">type T1 T2  // 传统的type defintion    vs.    type T1 = T2 //新增的type alias  </code></pre>    <p>把握住一点:<strong>传统的type definition创造了一个“新类型”,而type alias并没有创造出“新类型”</strong>。如果我们有一个名为“孙悟空”的类型,那么我们可以写出如下有意思的代码:</p>    <pre>  <code class="language-go">type  超级赛亚人  孙悟空  type  卡卡罗特 = 孙悟空  </code></pre>    <p>这时,我们拥有了两个类型:<strong>孙悟空</strong>和<strong>超级赛亚人</strong>。我们以孙悟空这个类型为蓝本定义一个超级赛亚人类型;而当我们用到<strong>卡卡罗特</strong>这个alias时,实际用的就是<strong>孙悟空</strong>这个类型,因为卡卡罗特就是孙悟空,孙悟空就是卡卡罗特。</p>    <p>我们用几个小例子再来仔细对比一下:</p>    <h3>1、赋值</h3>    <p>Go强调“显式类型转换”,因此采用传统type definition定义的<strong>新类型</strong>在其变量被赋值时需对右侧变量进行显式转型,否则编译器就会报错。</p>    <pre>  <code class="language-go">//github.com/bigwhite/experiments/go19-examples/typealias/typedefinitions-assignment.go  package main    // type definitions  type MyInt int  type MyInt1 MyInt    func main() {      var i int = 5      var mi MyInt = 6      var mi1 MyInt1 = 7        mi = MyInt(i)  // ok      mi1 = MyInt1(i) // ok      mi1 = MyInt1(mi) // ok        mi = i   //Error: cannot use i (type int) as type MyInt in assignment      mi1 = i  //Error: cannot use i (type int) as type MyInt1 in assignment      mi1 = mi //Error: cannot use mi (type MyInt) as type MyInt1 in assignment  }  </code></pre>    <p>而type alias并未创造新类型,只是源类型的“别名”,在类型信息上与源类型一致,因此可以直接赋值:</p>    <pre>  <code class="language-go">//github.com/bigwhite/experiments/go19-examples/typealias/typealias-assignment.go  package main    import "fmt"    // type alias  type MyInt = int  type MyInt1 = MyInt    func main() {      var i int = 5      var mi MyInt = 6      var mi1 MyInt1 = 7        mi = i // ok      mi1 = i // ok      mi1 = mi // ok        fmt.Println(i, mi, mi1)  }  </code></pre>    <h3>2、类型方法</h3>    <p>Go1中通过type definition定义的新类型,新类型不会“继承”源类型的<a href="/misc/goto?guid=4959754601976021577">method set</a>:</p>    <pre>  <code class="language-go">// github.com/bigwhite/experiments/go19-examples/typealias/typedefinition-method.go  package main    // type definitions  type MyInt int  type MyInt1 MyInt    func (i *MyInt) Increase(a int) {      *i = *i + MyInt(a)  }    func main() {      var mi MyInt = 6      var mi1 MyInt1 = 7      mi.Increase(5)      mi1.Increase(5) // Error: mi1.Increase undefined (type MyInt1 has no field or method Increase)  }  </code></pre>    <p>但是通过type alias方式得到的类型别名却拥有着源类型的method set(因为本就是一个类型),并且通过alias type定义的method也会反映到源类型当中:</p>    <pre>  <code class="language-go">// github.com/bigwhite/experiments/go19-examples/typealias/typealias-method1.go  package main    type Foo struct{}  type Bar = Foo    func (f *Foo) Method1() {  }    func (b *Bar) Method2() {  }    func main() {      var b Bar      b.Method1() // ok        var f Foo      f.Method2() // ok  }  </code></pre>    <p>同样对于源类型为非本地类型的,我们也无法通过type alias为其增加新method:</p>    <pre>  <code class="language-go">//github.com/bigwhite/experiments/go19-examples/typealias/typealias-method.go  package main    type MyInt = int    func (i *MyInt) Increase(a int) { // Error: cannot define new methods on non-local type int      *i = *i + MyInt(a)  }    func main() {      var mi MyInt = 6      mi.Increase(5)  }    </code></pre>    <h3>3、类型embedding</h3>    <p>有了上面关于类型方法的结果,其实我们也可以直接知道在类型embedding中type definition和type alias的差异。</p>    <pre>  <code class="language-go">// github.com/bigwhite/experiments/go19-examples/typealias/typedefinition-embedding.go  package main    type Foo struct{}  type Bar Foo    type SuperFoo struct {      Bar  }    func (f *Foo) Method1() {  }    func main() {      var s SuperFoo      s.Method1() //Error: s.Method1 undefined (type SuperFoo has no field or method Method1)  }  </code></pre>    <p>vs.</p>    <pre>  <code class="language-go">// github.com/bigwhite/experiments/go19-examples/typealias/typealias-embedding.go    package main    type Foo struct{}  type Bar = Foo    type SuperFoo struct {      Bar  }    func (f *Foo) Method1() {  }    func main() {      var s SuperFoo      s.Method1() // ok  }  </code></pre>    <p>通过type alias得到的alias Bar在被嵌入到其他类型中,其依然携带着源类型Foo的<a href="/misc/goto?guid=4959754601976021577">method set</a>。</p>    <h3>4、接口类型</h3>    <p>接口类型的identical的定义决定了无论采用哪种方法,下面的赋值都成立:</p>    <pre>  <code class="language-go">// github.com/bigwhite/experiments/go19-examples/typealias/typealias-interface.go  package main    type MyInterface interface{      Foo()  }    type MyInterface1 MyInterface  type MyInterface2 = MyInterface    type MyInt int    func (i *MyInt)Foo() {    }    func main() {      var i MyInterface = new(MyInt)      var i1 MyInterface1 = i // ok      var i2 MyInterface2 = i1 // ok        print(i, i1, i2)  }    </code></pre>    <h3>5、exported type alias</h3>    <p>前面说过type alias和源类型几乎是一样的,type alias有一个特性:可以通过声明exported type alias将package内的unexported type导出:</p>    <pre>  <code class="language-go">//github.com/bigwhite/experiments/go19-examples/typealias/typealias-export.go  package main    import (      "fmt"        "github.com/bigwhite/experiments/go19-examples/typealias/mylib"  )    func main() {      f := &mylib.Foo{5, "Hello"}      f.String()            // ok      fmt.Println(f.A, f.B) // ok        // Error:  f.anotherMethod undefined (cannot refer to unexported field      // or method mylib.(*foo).anotherMethod)      f.anotherMethod()  }    </code></pre>    <p>而mylib包的代码如下:</p>    <pre>  <code class="language-go">package mylib    import "fmt"    type foo struct {      A int      B string  }    type Foo = foo    func (f *foo) String() {      fmt.Println(f.A, f.B)  }    func (f *foo) anotherMethod() {  }  </code></pre>    <h2>二、Parallel Complication(并行编译)</h2>    <p><a href="/misc/goto?guid=4959754601475774362">Go 1.8版本</a>的gc compiler的编译性能虽然照比<a href="/misc/goto?guid=4958961622229086958">Go 1.5</a>刚自举时已经提升了一大截儿,但依然有提升的空间,虽然Go team没有再像<a href="/misc/goto?guid=4959754602100594041">Go 1.6</a>时对改进compiler性能那么关注。</p>    <p>在Go 1.9中,在原先的支持包级别的并行编译的基础上又实现了包函数级别的并行编译,以更为充分地利用多核资源。默认情况下并行编译是enabled,可以通过GO19CONCURRENTCOMPILATION=0关闭。</p>    <p>在aliyun ECS一个4核的vm上,我们对比了一下并行编译和关闭并行的差别:</p>    <pre>  <code class="language-go"># time GO19CONCURRENTCOMPILATION=0 go1.9beta2 build -a std    real    0m16.762s  user    0m28.856s  sys    0m4.960s    # time go1.9beta2 build -a std    real    0m13.335s  user    0m29.272s  sys    0m4.812s  </code></pre>    <p>可以看到开启并行编译后,gc的编译性能约提升20%(realtime)。</p>    <p>在我的Mac 两核pc上的对比结果如下:</p>    <pre>  <code class="language-go">$time GO19CONCURRENTCOMPILATION=0 go build -a std    real    0m16.631s  user    0m36.401s  sys    0m8.607s    $time  go build -a std    real    0m14.445s  user    0m36.366s  sys    0m7.601s  </code></pre>    <p>提升大约13%。</p>    <h2>三、”./…”不再匹配vendor目录</h2>    <p>自从<a href="/misc/goto?guid=4958961622229086958">Go 1.5</a>引入<a href="/misc/goto?guid=4959754602201203780">vendor机制</a>以来,Go的<a href="/misc/goto?guid=4959754602278574431">包依赖问题</a>有所改善,但在vendor机制的细节方面依然有很多提供的空间。</p>    <p>比如:我们在go test ./…时,我们期望仅执行我们自己代码的test,但Go 1.9之前的版本会匹配repo下的vendor目录,并将vendor目录下的所有包的test全部执行一遍,以下面的repo结构为例:</p>    <pre>  <code class="language-go">$tree vendor-matching/  vendor-matching/  ├── foo.go  ├── foo_test.go  └── vendor      └── mylib          ├── mylib.go          └── mylib_test.go  </code></pre>    <p>如果我们使用go 1.8版本,则go test ./…输出如下:</p>    <pre>  <code class="language-go">$go test ./...  ok      github.com/bigwhite/experiments/go19-examples/vendor-matching    0.008s  ok      github.com/bigwhite/experiments/go19-examples/vendor-matching/vendor/mylib    0.009s  </code></pre>    <p>我们看到,go test将vendor下的包的test一并执行了。关于这点,gophers们在go repo上提了很多<a href="/misc/goto?guid=4959754602357776032" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">issue</a>,但go team最初并没有理会这个问题,只是告知用下面的解决方法:</p>    <pre>  <code class="language-go">$go test $(go list ./... | grep -v /vendor/)  </code></pre>    <p>不过在社区的强烈要求下,Go team终于妥协了,并承诺在<a href="/misc/goto?guid=4959754602443619322" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">Go 1.9中fix该issue</a>。这样在Go 1.9中,你会看到如下结果:</p>    <pre>  <code class="language-go">$go test ./...  ok      github.com/bigwhite/experiments/go19-examples/vendor-matching    0.008s  </code></pre>    <p>这种不再匹配vendor目录的行为不仅仅局限于go test,而是适用于所有官方的go tools。</p>    <h2>四、GC性能</h2>    <p><a href="/misc/goto?guid=4959754602544634288">GC</a>在Go 1.9中依旧继续优化和改善,大多数程序使用1.9编译后都能得到一定程度的性能提升。1.9 release note中尤其提到了大内存对象分配性能的显著提升。</p>    <p>在”<a href="/misc/goto?guid=4959754602626854385">go runtime metrics</a>“搭建一文中曾经对比过几个版本的GC,从我的这个个例的图中来看,Go 1.9与Go 1.8在GC延迟方面的指标性能相差不大:</p>    <p><img alt="Go 1.9中值得关注的几个变化" src="https://simg.open-open.com/show/af49336a7ed101bab3df85f5cceebc65.png"></p>    <h2>五、其他</h2>    <p>下面是Go 1.9的一些零零碎碎的改进,这里也挑我个人感兴趣的说说。</p>    <h3>1、Go 1.9的新安装方式</h3>    <p>go 1.9的安装增加了一种新方式,至少beta版支持,即通过go get&download安装:</p>    <pre>  <code class="language-go"># go get golang.org/x/build/version/go1.9beta2    # which go1.9beta2  /root/.bin/go18/bin/go1.9beta2  # go1.9beta2 version  go1.9beta2: not downloaded. Run 'go1.9beta2 download' to install to /root/sdk/go1.9beta2    # go1.9beta2 download  Downloaded 0.0% (15208 / 94833343 bytes) ...  Downloaded 4.6% (4356956 / 94833343 bytes) ...  Downloaded 34.7% (32897884 / 94833343 bytes) ...  Downloaded 62.6% (59407196 / 94833343 bytes) ...  Downloaded 84.6% (80182108 / 94833343 bytes) ...  Downloaded 100.0% (94833343 / 94833343 bytes)  Unpacking /root/sdk/go1.9beta2/go1.9beta2.linux-amd64.tar.gz ...  Success. You may now run 'go1.9beta2'    # go1.9beta2 version  go version go1.9beta2 linux/amd64    # go1.9beta2 env GOROOT  /root/sdk/go1.9beta2  </code></pre>    <p>go1.9 env输出支持json格式:</p>    <pre>  <code class="language-go"># go1.9beta2 env -json  {      "CC": "gcc",      "CGO_CFLAGS": "-g -O2",      "CGO_CPPFLAGS": "",      "CGO_CXXFLAGS": "-g -O2",      "CGO_ENABLED": "1",      "CGO_FFLAGS": "-g -O2",      "CGO_LDFLAGS": "-g -O2",      "CXX": "g++",      "GCCGO": "gccgo",      "GOARCH": "amd64",      "GOBIN": "/root/.bin/go18/bin",      "GOEXE": "",      "GOGCCFLAGS": "-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build750457963=/tmp/go-build -gno-record-gcc-switches",      "GOHOSTARCH": "amd64",      "GOHOSTOS": "linux",      "GOOS": "linux",      "GOPATH": "/root/go",      "GORACE": "",      "GOROOT": "/root/sdk/go1.9beta2",      "GOTOOLDIR": "/root/sdk/go1.9beta2/pkg/tool/linux_amd64",      "PKG_CONFIG": "pkg-config"  }  </code></pre>    <h3>2、go doc支持查看struct field的doc了</h3>    <p>我们使用Go 1.8查看net/http包中struct Response的某个字段Status:</p>    <pre>  <code class="language-go"># go doc net/http.Response.Status  doc: no method Response.Status in package net/http  exit status 1  </code></pre>    <p>Go 1.8的go doc会报错! 我们再来看看Go 1.9:</p>    <pre>  <code class="language-go"># go1.9beta2 doc net/http.Response.Status  struct Response {      Status string  // e.g. "200 OK"  }    # go1.9beta2 doc net/http.Request.Method  struct Request {      // Method specifies the HTTP method (GET, POST, PUT, etc.).      // For client requests an empty string means GET.      Method string  }    </code></pre>    <h3>3、核心库的变化</h3>    <p>a) 增加monotonic clock支持</p>    <p>在2017年new year之夜,欧美知名CDN服务商<a href="/misc/goto?guid=4958879154768670414" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://www.cloudflare.com']);">Cloudflare</a>的<a href="/misc/goto?guid=4959754602743148058" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://blog.cloudflare.com']);">DNS出现大规模故障</a>,导致欧美很多网站无法正常被访问。之后,Cloudflare工程师分析了问题原因,罪魁祸首就在于golang time.Now().Sub对时间的度量仅使用了wall clock,而没有使用monotonic clock,导致返回负值。而引发异常的事件则是新年夜际授时组织在全时间范围内添加的那个闰秒(leap second)。一般来说,wall clock仅用来告知时间,mnontonic clock才是用来度量时间流逝的。为了从根本上解决问题,Go 1.9在time包中实现了<a href="/misc/goto?guid=4959010501197960533" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">用monotonic clock来度量time流逝</a>,这以后不会出现时间的“负流逝”问题了。这个改动不会影响到gopher对timer包的方法层面上的使用。</p>    <p>b) 增加math/bits包</p>    <p>在一些算法编程中,经常涉及到对bit位的操作。Go 1.9提供了高性能math/bits package应对这个问题。关于bits操作以及算法,可以看看经典著作<a href="/misc/goto?guid=4959754602855521892" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://book.douban.com']);">《Hacker’s Delight》</a>。这里就不举例了。</p>    <p>c) 提供了一个支持并发的Map类型</p>    <p>Go原生的map不是goroutine-safe的,尽管在之前的版本中陆续加入了对map并发的检测和提醒,但gopher一旦需要并发map时,还需要自行去实现。在Go 1.9中,标准库提供了一个支持并发的Map类型:sync.Map。sync.Map的用法比较简单,这里简单对比一下builtin map和sync.Map在并发环境下的性能:</p>    <p>我们自定义一个简陋的支持并发的类型:MyMap,来与sync.Map做对比:</p>    <pre>  <code class="language-go">// github.com/bigwhite/experiments/go19-examples/benchmark-for-map/map_benchmark.go  package mapbench    import "sync"    type MyMap struct {      sync.Mutex      m map[int]int  }    var myMap *MyMap  var syncMap *sync.Map    func init() {      myMap = &MyMap{          m: make(map[int]int, 100),      }        syncMap = &sync.Map{}  }    func builtinMapStore(k, v int) {      myMap.Lock()      defer myMap.Unlock()      myMap.m[k] = v  }    func builtinMapLookup(k int) int {      myMap.Lock()      defer myMap.Unlock()      if v, ok := myMap.m[k]; !ok {          return -1      } else {          return v      }  }    func builtinMapDelete(k int) {      myMap.Lock()      defer myMap.Unlock()      if _, ok := myMap.m[k]; !ok {          return      } else {          delete(myMap.m, k)      }  }    func syncMapStore(k, v int) {      syncMap.Store(k, v)  }    func syncMapLookup(k int) int {      v, ok := syncMap.Load(k)      if !ok {          return -1      }        return v.(int)  }    func syncMapDelete(k int) {      syncMap.Delete(k)  }    </code></pre>    <p>针对上面代码,我们写一些并发的benchmark test,用伪随机数作为key:</p>    <pre>  <code class="language-go">// github.com/bigwhite/experiments/go19-examples/benchmark-for-map/map_benchmark_test.go  package mapbench    import "testing"    func BenchmarkBuiltinMapStoreParalell(b *testing.B) {      b.RunParallel(func(pb *testing.PB) {          r := rand.New(rand.NewSource(time.Now().Unix()))          for pb.Next() {              // The loop body is executed b.N times total across all goroutines.              k := r.Intn(100000000)              builtinMapStore(k, k)          }      })  }    func BenchmarkSyncMapStoreParalell(b *testing.B) {      b.RunParallel(func(pb *testing.PB) {          r := rand.New(rand.NewSource(time.Now().Unix()))          for pb.Next() {              // The loop body is executed b.N times total across all goroutines.              k := r.Intn(100000000)              syncMapStore(k, k)          }      })  }  ... ...    </code></pre>    <p>我们执行一下benchmark:</p>    <pre>  <code class="language-go">$go test -bench=.  goos: darwin  goarch: amd64  pkg: github.com/bigwhite/experiments/go19-examples/benchmark-for-map  BenchmarkBuiltinMapStoreParalell-4         3000000           515 ns/op  BenchmarkSyncMapStoreParalell-4            2000000           754 ns/op  BenchmarkBuiltinMapLookupParalell-4        5000000           396 ns/op  BenchmarkSyncMapLookupParalell-4          20000000            60.5 ns/op  BenchmarkBuiltinMapDeleteParalell-4        5000000           392 ns/op  BenchmarkSyncMapDeleteParalell-4          30000000            59.9 ns/op  PASS  ok      github.com/bigwhite/experiments/go19-examples/benchmark-for-map    20.550s  </code></pre>    <p>可以看出,除了store,lookup和delete两个操作,sync.Map都比我自定义的粗糙的MyMap要快好多倍,似乎sync.Map对read做了特殊的优化(粗略看了一下代码:在map read这块,sync.Map使用了无锁机制,这应该就是快的原因了)。</p>    <p>d) 支持profiler labels</p>    <p>通用的<a href="/misc/goto?guid=4959754602940874432">profiler</a>有时并不能完全满足需求,我们时常需要沿着“业务相关”的执行路径去Profile。Go 1.9在runtime/pprof包、go tool pprof工具增加了对label的支持。Go team成员<a href="/misc/goto?guid=4959717429163387227" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://推ter.com']);">rakyll</a>有一篇文章<a href="/misc/goto?guid=4959754603045876061" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://rakyll.org']);">“Profiler labels in go”</a>详细介绍了profiler labels的用法,可以参考,这里不赘述了。</p>    <h2>六、后记</h2>    <p>正在写这篇文章之际,<a href="/misc/goto?guid=4959754603143384901" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://推ter.com']);">Russ Cox</a>已经在<a href="/misc/goto?guid=4959754603226940894" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://推ter.com']);">GopherCon 2017大会</a>上做了”The Future of Go”的演讲,并announce Go2大幕的开启,虽然只是号召全世界的gopher们一起help and plan go2的设计和开发。同时,该演讲的文字版已经在<a href="/misc/goto?guid=4958865861071770650" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://golang.org']);">Go官网</a>发布了,文章名为<a href="/misc/goto?guid=4959009844110964620" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://blog.golang.org']);">《Toward Go 2》</a>,显然这又是Go语言演化史上的一个里程碑的时刻,值得每个gopher为之庆贺。不过Go2这枚靴子真正落地还需要一段时间,甚至很长时间。当下,我们还是要继续使用和改善Go1,就让我们从Go 1.9开始吧^0^。</p>    <p>本文涉及的demo代码可以在<a href="/misc/goto?guid=4959754603360666710" onclick="javascript:_gaq.push(['_trackEvent','outbound-article','http://github.com']);">这里</a>下载。</p>    <p>来自:<a href="/misc/goto?guid=4959754603454064130" title="Go 1.9中值得关注的几个变化">Go 1.9中值得关注的几个变化</a></p>