Golang function Variable parameter transfer performance problem

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

A few days ago tangled up an egg ache problem, in go inside function type supports variable parameter, for example ... T,go creates a slice that holds incoming mutable arguments, so if you create a slice, such as a, then a ... In this way, go will not also create a new slice, will be A's data all copy a copy of the past?

If a is very large, then it will cause very serious performance problems, but later think, may be self-worried, so look at the go document, found the following things:

Passing arguments to ... parameters

If F is variadic with a final parameter p of type ... T, then within F the type of P was equivalent to type []t. If F is invoked with no actual arguments for P, the value of passed to P is nil. Otherwise, the value passed is a new slice of type []t with a new underlying array whose successive elements are the Actua L arguments, which all must is assignable to T. The length and capacity of the slice is therefore, the number of arguments bound to p, and may differ for each call site.

Given the function and calls

func Greeting(prefix string, who ...string)Greeting("nobody")Greeting("hello:", "Joe", "Anna", "Eileen")

Within greeting, who would has the value nil in the first call, and []string{"Joe", "Anna", "Eileen"} in the second.

If The final argument is assignable to a slice type []t, it could be passed unchanged as the value for a ... T parameter if the argument is followed by .... In this case no new slice is created.

Given the slice s and call

s := []string{"James", "Jasmine"}Greeting("goodbye:", s...)

Within greeting, who'll has the same value as s with the same underlying array.

package mainimport "FMT" func t (args ... int) {FMT.    Printf ("%p\n", args)}func main () {a: = []int{1,2,3} b: = a[1:] t (a ...)    T (b ...) Fmt. Printf ("%p\n", a) fmt. Printf ("%p\n", b)}//output0x1052e1200x1052e1240x1052e1200x1052e124  

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.