A simple example of the idea of object reuse in Go

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

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)} ()}

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.