Interpretation of the Golang of 2016: The speed of ascension, gradually beyond

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The go language is 7 years old! In August this year, Go 1.7 was released as scheduled. At the time of writing, the beta version of Go 1.8 came out. We are eagerly looking forward to the Go 1.8 official version next February.

If you focus on the Tiobe programming language leaderboard will find that as of November 2016, the go language from the original more than 50 after many times have jumped to the 13th place, Atoda into the ranks of the absolute mainstream programming language! The rankings are updated every month, and are ranked based on the number of veteran, teaching, and related vendors on the Internet. In China, from the experience of running the Go language Beijing user group in the past few years, I can obviously feel the great heat of the go language in the country. N Many start-up internet companies use the go language as their basic technology stack. I also found that domestic companies already working in cutting-edge technologies such as big data and robotics began to use the go language. The language is now all-pervasive.

1. Review

Thinking back last year's 1.5 release, the Go runtime system and the standard library were just finished to C, and instead were completely rewritten by the go language and assembly language. Up to now, the go source code has been greatly improved, the go language version of the go language is more mature. Let me take a look at the big moves that the go language made in 2016. You can compare my previous written "interpretation of the Golang of 2015: Golang of the full burst of time" to see.

1.1 Fast GC

Of course, the first thing to say is performance. The biggest performance boost in the Go language itself is still in the GC (garbage collection, garbage collection). The GC, which was advertised from Go 1.5, took hundreds of milliseconds, and today's full concurrent GC makes it time-consuming to get to the millisecond level, and then to the upcoming go 1.8, with a lot of improvements, the GC-time of the next hundred microseconds is just a leap ahead!

Figure 1 GC Pause time--go 1.5 vs. Go 1.6

Figure 2 GC Pause time--go 1.7

After all this change, if you say now that your go program's performance bottlenecks are on the GC, that can only make a person's mind.

Of course, the go language improves its performance much more than that.

1.2 Support for HTTP/2

Long ago, the go language team began to follow up on draft HTTP/2. Starting with Go 1.6, we have been able to use the HTTP/2 in the Go program indirectly, such as: Using the GO program to develop the HTTPS protocol-based server and client. However, all of this is automatically adapted, and go does not reveal any APIs that can specify or configure the HTTP/2 module. In addition, HTTP/2 will receive more extensive support in the not-yet-released go 1.8.

1.3 HttpTrace Bag

The Net/http/httptrace Code package (Https://godoc.org/net/http/httptrace) has been added to the standard library of Go 1.7. It provides a way to debug HTTP requests and responses. You can easily get detailed information about the HTTP protocol-based communication process as follows.

Package Mainimport ("context" "FMT" "Log" "Net/http" "Net/http/httptrace" "OS") Func main () {tracectx: = HttpTrace. Withclienttrace (context. Background (), &httptrace. Clienttrace{getconn:func (Hostport string) {fmt. Printf ("Prepare to get a connection for%s.\n", Hostport)},gotconn:func (Info HttpTrace.) Gotconninfo) {fmt. Printf ("Got a connection:reused:%v, from the Idle pool:%v.\n", info. Reused, Info. Wasidle)},putidleconn:func (err error) {if Err = = Nil {fmt. Println ("Put a connection to the idle Pool:ok.")} else {fmt. Println ("Put a connection to the idle pool:", err.) Error ())}},connectstart:func (network, addr string) {Fmt. Printf ("Dialing ... (%s:%s). \ n ", network, addr)},connectdone:func (network, addr string, err error) {if Err = = Nil {fmt. Printf ("Dial is done. (%s:%s) \ n ", network, addr)} else {fmt. Printf ("Dial is do with error:%s. (%s:%s) \ n", err, network, addr)}},wroterequest:func (Info HttpTrace.) Wroterequestinfo) {if info. ERR = = Nil {fmt. Println ("wrote a Request:ok.")} else {fmt. PrinTLN ("wrote a request:", info.) Err.error ())}},gotfirstresponsebyte:func () {fmt. Println ("Got the first response byte.")}, req, err: = http. Newrequest ("GET", "http://www.golang.org/", nil) if err! = Nil {log. Fatal ("Fatal error:", err)}req = req. Withcontext (Tracectx) _, Err = http. Defaultclient.do (req) If err! = Nil {fmt. fprintf (OS. Stderr, "Request Error:%v\n", err) OS. Exit (1)}}

It is highly recommended that you run this applet and enjoy the feeling of mastering the overall situation.

1.4 Sub-Test

Go 1.7 adds support for child testing (https://blog.golang.org/subtests), including functional testing and performance testing. The primary purpose of the sub-test is to differentiate and present the different test results that result from different test parameters or test data in the test function. Please see the test procedure below.

Package Subtestimport ("FMT" "Math/rand" "StrConv" "testing")//KE represents key-element pair. The type KE struct {key     stringelement int}//benchmarkmapput is used to test the addition and modification of the dictionary. Func Benchmarkmapput (b *testing. B) {max: = 5var Kes []kefor I: = 0; I <= max; i++ {kes = append (Kes, Ke{strconv. Itoa (i), Rand. INTN (1000000)})}m: = Make (Map[string]int) B.resettimer () for _, ke: = Range Kes {k, E: = Ke.key, Ke.elementb.Run (FMT. Sprintf ("Key:%s, Element:% #v", K, E), func (b *testing. B) {for i: = 0; i < B.N; i++ {M[k] = e + i}}}}

Use the Go test-run=^$-bench in the directory where the program is located. After you run it, you'll see that the Go Test command prints a single line of test summaries for each sub-test. They are separated and independently counted. This allows us to perform a more granular test, fine-grained to each input and output. The above print content is similar:

Benchmarkmapput/key:_0425,_element:_498081-4         30000000        40.6 ns/opbenchmarkmapput/key:_1540,_element:_ 727887-4         30000000        41.7 ns/opbenchmarkmapput/key:_2456,_element:_131847-4         30000000        43.3 ns/ Opbenchmarkmapput/key:_3300,_element:_984059-4         30000000        46.1 ns/opbenchmarkmapput/key:_4694,_element:_ 902081-4         30000000        48.4 ns/opbenchmarkmapput/key:_5511,_element:_941318-4         30000000        59.3 ns/ Oppassok  _/users/haolin/infoq-2016_review_go/demo/subtest8.678s

1.5 Vendor Directory

At Go 1.5, the official enabled a new environment variable,--go15vendorexperiment. This environment variable can start the Go Vendor directory (Https://golang.org/s/go15vendor) and is used to hold the code package that the current code package relies on. In Go 1.5, if the value of Go15vendorexperiment is 1, the vendor directory is started. Go 1.6 In contrast, the vendor directory is supported by default, and the vendor directory is disabled when the value of Go15vendorexperiment is 0 o'clock. To go 1.7, the official completely removed the environment variable. This also represents a formal support for the vendor catalogue. The experimental features of the Go language are generally followed by a similar approach to the official version.

1.6 Other improvements worth mentioning

1.6.1 detects and reports non-concurrent secure access to dictionaries

Starting with Go 1.6, the Go runtime system takes a 0 tolerance of non-concurrent security access to the dictionary. Please see the procedure below.

Package Mainimport "Sync" func main () {const WORKERS = 100var WG sync. Waitgroupwg.add (Workers) m: = map[int]int{}for I: = 1; I <= workers; i++ {go func (i int) {for j: = 0; J < i; J + + {M[I]++}WG. Done ()} (i)}WG. Wait ()}

The program accesses the dictionary instance m concurrently in multiple goroutine without any protection being applied. We know that the dictionary type of Go native is non-concurrency safe. So the above is likely to cause an unpredictable change in the value of M. This should be resolutely avoided in concurrent programs. Before 1.6, the GO program did not crash. However, at 1.6, the program crashes immediately after running the above program. The Go runtime system will force the end of the program and report an error whenever a similar code is detected.

1.6.2 the performance improvement of the sort package

The Go language team has been committed to improving the performance of many APIs in the standard library and has always been a significant result. I took the sort parcel out to emphasize it because of sort. The sort function adjusts slightly in behavior because of performance optimizations. On Go 1.6,sort. The sort function reduces the number of comparison operations and switching operations by approximately 10%, resulting in 20%~50% performance gains. However, there is a side effect, and that is sort. Execution of the sort function causes the sorting algorithm to be unstable. The so-called unstable sorting algorithm is that the ordering of multiple elements that may make the ordering factor equal is indeterminate in order. For example, there are slices of strings that need to be sorted by length:

var langs= []string{"Golang", "Erlang", "Java", "Python", "PHP", "C + +", "Perl"}

by sort. After the sort function is sorted, the slice is only a few elements of equal length Golang, Erlang, and Python may not be the same, and may become Erlang, Golang, Python. Although it will still be sorted exactly by the sort factor (here is the length of the string), it can actually affect some programs.

If you need a stable sort, you can use sort. Stable function instead.

1.6.3 context package into the standard library

When Go 1.7 was released, a code package named context already appeared in the standard library. The code package originally had an import path of Golang.org/x/context, which now does not exist. The context package was formally introduced into the standard library, and many of the APIs in the standard library were changed. Context. The value of the context type can coordinate code in multiple groutine to perform a "cancel" operation, and can store key-value pairs. The most important thing is that it is concurrency-safe. APIs that work with it can be "canceled" by external controls, such as canceling the execution of an HTTP request.

1.6.4 Go Tool Trace enhancements

Go tool Trace has become another tool for Go program debugging since go 1.5 was formally added. To go 1.7, it has been greatly enhanced. For example, the execution time is shortened, the tracking information is rich, and so on.

1.6.5 Unicode packets are now based on Unicode 9.0

Go 1.7 Upgrades The Unicode package so that it supports the Unicode 9.0 standard. Prior to this, it supported the Unicode 8.0 standard.

1.6.6 new compiler back-end--ssa

The SSA , as a new compiler backend, allows the compiler to generate code that is more efficient in compression and execution, and provides stronger support for further optimizations in the future. In terms of performance, it allows the program to reduce CPU usage by 5% to 35%.

Here, I show you some notable changes in the go language in the 2016. There are many changes to the Go Runtime system and the standard library that are not mentioned because of the space reasons. In particular, performance improvements have been ongoing and have subtly provided the underlying bonuses for the vast majority of go programmers.

I strongly recommend that all go programmers follow the footsteps of the Go Language team, upgrade the version and enjoy the bonus.

2. Outlook

2.1 New version

As for the outlook, there is no more go 1.8 that the go programmer eagerly expects. Here are some of the features that are like showers.

    1. The go-written HTTP server supports smooth shutdown. This feature has long been implemented by a number of third-party code packages, but this time the authorities have finally given the answer.
    2. Support for HTTP/2 server Push. This is not much to say, it will certainly be better than hijack.
    3. With the addition of the plugin package, you can dynamically load some go programs into your program as plugins.
    4. Broader context support, since the standard library has a context package, it has worked in many places. Many standard library-based interface functions can perform a "cancel" operation. In Go 1.8, the scope will be further expanded, for example: the Database/sql package and the testing package both support the context.
    5. The functionality of the sort package is improved, and for slicing, we no longer have to write the implementation type of an interface in order to use its sort function.
    6. The Go Test command has a new tag:-mutexprofile. This tag is used to provide a profile for lock contention.
    7. Of course, the most desirable is still the performance of go to improve, especially in the GC, but also a leap! In addition, the defer statement executes twice as fast as before! CGO's call overhead is also reduced by almost half!

2.2 Technical Community

In fact, in addition to the vision of the go language itself, we should also look forward to the development of the go Community (especially the domestic go community). China is now almost the most visited country for go programmers.

If you open the Go language wiki on GitHub (https://github.com/golang/go/wiki/GoUsers), you will find that there is already a very long list. The company reached nearly 200, compared with nearly three times times the end of 2015. And I believe this is only a small part of the company that has its own official organization on GitHub and contributes to the community. However, you may also find that there is only one company under the China column. What is this for? The comparison is worth pondering. I think this may reflect the problem of too few domestic companies contributing to the international technology community, especially the open source community. At the podium of a big open-source technology event in early December 2016, an open-source company CEO mentioned that programmers should be more dedicated to the open-source community, so that they could better advertise and market themselves. At the same time, the Organization should not become a bottleneck for everyone to cooperate. However, I think the actual situation at home is exactly the opposite. Our domestic computer technology companies, and even technology-driven internet companies, most of them do not contribute to the open source community, even from the rules and regulations are expressly prohibited. From this perspective, I think the horror of the China column in that list is not the same. I eagerly hope that the China column will grow a lot longer next year.

However, in terms of the number of GO projects on GitHub and some of the domestic code-hosting warehouses, there is actually a lot of go software written by people in China. In recent years, the rise of domestic go open source projects have been many, especially (in terms of star number) Gogs, Beego, Tidb, Codis, Pholcus, Hprose, Cyclone and so on. They have had a certain influence at home or abroad. In addition, the national or Chinese participation in the international Go Open source project is numerous, such as many people know the container technology industry leader Docker, Kubernates, ETCD, and so on.

Of course, apart from some top-notch people and top-notch projects. Most Chinese go programmers and enthusiasts are still only active in the country. Many local countries have launched the Go Language user group, including but not limited to: Beijing, Shanghai, Shenzhen, Hangzhou, Dalian, Hong Kong and so on. Go language Technology gatherings are also more professional, more frequent, and larger at all locations. In Beijing alone, the number of people attending such gatherings or events in 2016 was more than 2000 fans of the 400,go language Beijing user group's public number (golang-beijing). It is learnt that in 2017, the Go Language user group in different places will have bigger action.

I personally think, now go language domestic promotion has basically completed the science stage, now we can implement more easily to promote, yielded promotion strategy. Thanks to the excellence of the Go language and its constant evolution, more and more people are now focusing on the go language, especially in the people of higher education and novice programmers.

Go language is very studious, complete supporting tools, development and operation of high efficiency, many applications, the domestic community is also very active, there are a variety of Chinese materials and tutorials, advanced is not difficult, and its engineering philosophy is quite popular. If you don't have a little time, I suggest you learn this simple, efficient programming language. In the Internet age, especially in the era of mobile internet, it has a vast prospect. It is also a very important technology stack, even for new areas and concepts like big Data and microservices. Even in the coming wave of AI and robotics, I believe the go language will shine!

Author Introduction

it , the initiator of the Go language Beijing user group, the Geek College Go language course consultant, is the author of the Turing original book "Go Concurrent Programming," and also the online free tutorial "Go command Tutorial" and "Go language first lesson". Currently in the micro-race era as the platform technology leader.

Reference documents

    1. Go 1.6 Release notes:https://tip.golang.org/doc/go1.6
    2. Go 1.7 Release notes:https://tip.golang.org/doc/go1.7
    3. Go 1.8 Release Notes (Beta): https://tip.golang.org/doc/go1.8
    4. The state of Go: Https://talks.golang.org/2016/state-of-go.slide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.