golang函數可變參數傳遞效能問題

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

幾天前糾結了一個蛋疼的問題,在go裡面函數式支援可變參數的,譬如...T,go會建立一個slice,用來存放傳入的可變參數,那麼,如果建立一個slice,例如a,然後以a...這種方式傳入,go會不會還會建立一個slice,將a的資料全部拷貝一份過去?

如果a很大,那麼將會造成很嚴重的效能問題,不過後來想想,可能是自己多慮了,於是查看go的文檔,發現如下東西:

Passing arguments to ... parameters

If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T. If f is invoked with no actual arguments for p, the value 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 actual arguments, which all must be 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 will have 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 may 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 will have the same value as s with the same underlying array.

也就是說,如果我們傳入的是slice...這種形式的參數,go不會建立新的slice。寫了一個簡單的例子驗證:

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

可以看到,可變參數args的地址跟實際外部slice的地址一樣,用的同一個slice。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.