Annual Language Golang Use feeling

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

First of all, there is no language dispute, after all, PHP is the world's best language, not one. This topic can be stopped.

2016 has passed, 16 of the annual language gave go语言 , and just this year I used to go with a lot more, and version from 1.2 has been used to 1.8, some feelings, say I have some superficial understanding of this year's programming language it. I also wrote a go language article before, but it was not used much at the time, some features were not used, so the understanding and today are somewhat different.

This article does not have any advantages and disadvantages, think of where to speak.

The pointers are still very important.

First look at a small hole, there may be a lot of first contact go will encounter, go range of the overlap is also a lot of, the following example does not know if you have encountered before, in fact, the value is not change, or a.

type a struct {    b int}func main() {    m := make([]a, 0)    m = append(m, a{b: 0, c: 0})    m = append(m, a{b: 1, c: 1})    m = append(m, a{b: 2, c: 2})    for _, e := range m {        e.b = 9    }    for _, x := range m {        fmt.Printf("%v\n", x.b)    }}

In range, the next element is the value of the transfer, this is very important, so the content of the element can not be modified, and if the element is large, the cost of the iteration is quite large, so either you become for idx, _ := range m such a form, with the subscript update, or become m := make([]*a, 0) such a pointer, so although the value of the pass, is just a pointer to the value, one is the cost is small, second, you can directly modify the element content.

So, the pointer in go is still an indispensable existence, which is why like me before the C and C + + people like go reason, because still can be the pointer flying, write can only understand the code to go out to install force, and then tell others, or there is a good pointer performance ah.

If you have no idea of the pointer, or have not understood the pointer, then go may be good or take a little time, go is really easy to get started, but it is not so easy to use, I started with the time, did not think carefully about this aspect of things, and deliberately reduce the use of pointers, fear of the presence of the wild pointer in C case , then the more you write the more I think it is not that flavor, go to the pointer this function or let you use it, and then write the code began to bias C style, the hands fly everywhere.

Nevertheless, for security reasons, go pointers still have some limitations, the conversion between the various types is not possible, like the C language, the various types of variables through the pointer is difficult to do directly, but still to the people who have this need to open a hole, that is the unsafe package, Look at the name of this bag to know is to warn you, it is not safe, ah, hang up don't come to me, I am out of this bag just to give you to install force.

For example, if we have a requirement that we need to sequence a struct array into a byte array, we need to restore it back, and the general practice is to serialize it into JSON or serialize it to binary with Gob, and then return it in deserialization, as the code normally does.

//do some append jsonbyte, err := json.Marshal(YYY)//do some thingstructArray,err:=json.Unmarshal(jsonbyte,&XXX)

First of all, the serialization and deserialization are costing resources, affecting the speed, but also a copy of the data, which for a high -performance language to write high-performance services How can endure, that can only sacrifice the pointer artifact, and also have to use the unsafe package to add halo, under normal circumstances, In the process of serialization, the copy will not run away, you do not need to serialize to itself, so the serialization of the time to go directly to a byte array, of course, the need to record length.

buffer := new(bytes.Buffer)err = binary.Write(buffer, binary.LittleEndian, YYY)lens=len(YYY)resBytes:=buffer.Buffer()

At this time, the YYY structure array is serialized into the resbytes byte array, the length is lens, when deserializing, directly with the pointer and the unsafe package on the line, the entire process has no data copy, there is no serialization and anti-sequence overhead, Just like the code below.

XXX := *(*[]structNode)(unsafe.Pointer(&reflect.SliceHeader{        Data: uintptr(unsafe.Pointer(&resBytes[0])),        Len:  int(lens),        Cap:  int(lens),    }))

Of course, this is suitable for the structNode structure of the elements inside is fixed-length, if the elements there is a byte array or string, or even int this and operating system architecture-related elements, it is really unsafe , hehe.

The above two examples tell us that the pointer is retained in the Golang, the development of strong demand for performance is still good, and, the unsafe function that the package opens up, at least can let you know the data in the bottom to exactly what address, in the heart also ground.

Map of the pit daddy

Read/write Security

For map is not the process of security this point, or some want to spit groove, the other language is not a lot of thread-safe, this is nothing to say, when you write the code to pay attention to it, but Golang itself is to co-process in the language integration, open the process is particularly easy language, and is to encourage people to use the process of thinking to programming, but as a basis for integration into the language itself data structure, unexpectedly is not the process security, I go, you provide at least a security version of the process to choose Ah, although the addition of read and write locks is easier to implement, but there are several problems:

    • There is a lock on the inevitable need to consider the situation of deadlock, and the problem is not well checked.

    • Due to the addition of defer reserved words, a lot of people in the use of locks is basically the lock and unlock written together, so sometimes the code to change, the logic flow changed, easy to lead to deadlock.

    • Some people say map itself can be encapsulated into a structure, switch lock will not see, but many times, just start to write the code is not required to multi-process, at this time you use the map is an internal map, when you find the need to lock the map, there are only two options, one is to encapsulate the map into a structure, And then all the use of this map of the place to get rid of, two is to add a lock outside, the conflict will be locked up, the first way to change some large, the second way may produce a bug.

If there is a choice of map implementation of the way, to compete when reading write safe, non-competition when the choice of simple rough.

Small pits of memory pools

Many times, because of the GC problem, we want to make a memory pool, the more mainstream approach is to use the pipeline to apply for the release of memory, and now has a sync.pool package.

But the pipeline to do the memory pool, only suitable for the array type of data, not for the map, because the array, you just need to put Len to 0,cap, spit out the line, this will reduce the memory application overhead, but the map, do not delete the key, this key is always in, So it's not possible to use a memory pool to apply for a map.

Of course, there is no language to support the map of the memory pool, but because go pipeline concept, so that everyone feel that anything can be lost in the memory pool when the way to support the map, the pit is big. Oh, I am ...

MAP and structure

If the value of a map is a struct, then you can not map[key].sturct.ele=XX give this map of the structure of the elements of the assignment, it is good to compile the language, will jump a compilation cannot assign to error come out, calculate a small pit bar, because the map will be used in the process of continuous application of new memory, Copying objects into new memory, so direct addressing is not supported.

About generics

No generics are a lot of people feel that go language is not human touch a place, I am also one of them, incredibly no generic, how do you tell people how to write a loaded, concise code? And Golang designers actually said not ready to support generics (but now seems to have changed, said Go2.0 will consider supporting generics, hehe), this is simply, why does not support generics, is interface{} enough? The constant type judgment inevitably leads to the code ugly and the performance loss, this is not clear? But.....

But if we think about the implementation of generics a little bit to understand them, first of all, the implementation of generics have two ways, one is C + + template mode, one is Java type erasure (like this name) way, we look at the two ways of generics, and then guess Golang why not support.

    • The generic implementation of C + + way is through the template, simple is to compile the time by analyzing the caller of the generic function, and then produce the corresponding function, the advantages and disadvantages are obvious.

      • The advantage is that you do not need to run the time to make the type of judgment to save the runtime time.

      • The main disadvantages are two points, one is the compilation time is longer, and the other is that if the type is many, it will cause the final generated code to become a lot.

    • Java generics are implemented by type erase, I am not writing Java itself, this part of the study is not very clear, only know that he is not a compile-time substitution type, but to erase the type, such as all into obj, In the run time needed to turn back (to Java this paragraph is not very sure ha), personally think is the type to turn *void , this does not erase, and then use the time to turn back on the line ha. The advantages and disadvantages are also obvious

      • The good thing is that the code doesn't swell.

      • The disadvantage is that, the runtime still needs to make the type of judgment, increase the consumption, may also be unsafe, because as long as it is run-time judgment, you are likely to an int type insert a string.

Well, we simply said the principle of generics, then if go to achieve generics, basically is the two ways, the second way is not feeling and interface a familiar bright? Well, it looks the same, there are essential differences, the second Java that way is JIT implementation, and interface is runtime implementation, the efficiency is not a little bit. What if the template extension is compiled in the first way? will also encounter the situation of code increase, Golang's target file is to integrate all things to come, it is very large, and so the whole, the estimated target file is larger.

I think even if the Golang open generics, the estimation is also used in the first way, because if the runtime of the way, the runtime scheduler to add a lot of pressure, and Golang certainly will not use the JIT bar, so the second way of implementation is estimated a bit tough.

Some of the other

For GC, do not spit groove, because after all, really have GC problem, I use CGO, hehe, or in the design of the time will be directly consider some modules with C to do, and the current go version, GC has been very good, most of the application is not a problem, Golang integration into the language, Will inevitably lead to everyone regardless of performance problems, unrestrained open the process, that this hole can only Google to fill out, the new version (1.8) of the GC support has been very good, but the performance of the service, some code, or use C bar, haha.

Of course, if go has a non-GC implementation, to manage the memory version, it is good, the syntax is more comfortable than C, and the co-process and pipeline these things, if you can manage the heap memory, it is perfect.

Finally, there are some unfinished, this is not said, next time talk about the channel and Goroutine, and C mixed programming.

If you feel good, welcome forwarded to more people to see, also welcome to pay attention to my public number, mainly talk about search, recommendation, advertising technology, and nonsense. The article will be sent first here:) scan or search for XJJ267 or search for the language of West Gaga .

Related Article

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.