Golang a large number of string concatenation methods

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Although convenient, using the + = operator is not the most efficient way to append a string to the end of a string in a loop, a valid way is to prepare a string slice ([]string) and then use strings. The Join () function concatenates all strings together at once. But there's a better way to go, which works like StringBuilder in Java.

Package Mainimport ("bytes" "FMT") func main () {var buffer bytes.  Buffer//buffer is a variable-sized byte buffer that implements a read-write method for {if piece, OK: = GetNextString (); ok {/*   func (b *buffer) writestring (s string) (n int, err error)   Write writes the contents of S to the buffer, increasing the buffer capacity if necessary. The return value n is Len (p), and err is always nil. If the buffer becomes too large, write uses the error value Errtoolarge to raise the panic. */buffer. WriteString (piece)} else {break}}fmt. PRINTLN ("Results after stitching", buffer.) String ())}

After testing, connect 1 million strings, use buffer to consume about 77 milliseconds, use + = consume time for ... I'm sorry, I waited 5 minutes and I didn't run out. After reducing the order of magnitude, the time to connect 100,000 strings is 3312 milliseconds

In addition, the string output in the Golang has a length limit, do not know the specific limit of how much, over 10 million length will not show, over 100 billion liteide crashes ...

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.