Originally wanted to write an example to the team of people to explain the object of Go in the idea of reuse, after writing found that this thought may be some students do not know, is now shared.
Go in order to reduce the amount of memory allocation, control garbage collection time, the idea of hot data pool to deal with is very good, the following example is a simple TCP read cache pool multiplexing//implemented a buffer pool to read TCP long connection, each time a new connection is read, First go to the pool read//If it does not exist, create a new//note BUF when the dominant is put back, zero processing is done because Conn. Read every time the read,//will start from the location of buf.b[0] to write the package mainimport ("FMT" "Net" "Sync") var bufpool sync. Pooltype buf struct {b []byte}func Main () {ln, _: = Net. Listen ("TCP", ": 8082") for {conn, err: = ln. Accept () if err! = Nil {fmt. PRINTLN ("Accept Error:", err)}//for each incoming connection opens a goroutine processing go func () {var bf *bufv: = Bufpool.get () if v = = Nil {//If there is no buf, create The new FMT. PRINTLN ("No buffer, need create!") BF = &buf{b:make ([]byte, Ten),}} else {//dominant exists buf,v here is interface{}, need to do type conversion BF = V. (*BUF)}//read data continuously from Conn//Note Conn. Read has a feature, if the bf.b capacity is insufficient, then will be divided into two reads//instead of expanding Bf.bfor {_, Err: = conn. Read (BF.B)//Here is just an example, so there is no on Io. EOF makes special treatment if err! = Nil {fmt. PRINTF ("conn Error:% #v", err) break}}//BF Mission accomplished, put into pool bufpool.put (BF)} ()}
A simple example of the object reuse idea of Go