LoginSignup
8
8

More than 5 years have passed since last update.

Go1.3beta1でappendの動きが変更されたようです

Posted at

内容

appendで追加されるキャパシティの量が変更されたようです。
具体的にはGo1.2.1では以下のコードで生成したスライスのキャパシティは「1」でしたが、Go1.3beta1では「8」になります。
a := append([]byte{}, 0)

また、Go1.2.1では以下のコードで生成したスライスのlen(a)とcap(a)が同じでしたが、Go1.3beta1では異なるようです。
a := append([]byte{}, []byte{1,2,3,4,5}...)

サンプルコード

unko.go
package main

import (
    "fmt"
)

func main() {
    buf := []byte{1,2,3,4,5,6,7,8,9}

    fmt.Println("===a===")
    a := make([]byte, len(buf))
    copy(a, buf)
    fmt.Printf("len:%d, cap:%d\n", len(a), cap(a))

    fmt.Println("===b===")
    b := make([]byte, 0, len(buf))
    b = append(b, buf...)
    fmt.Printf("len:%d, cap:%d\n", len(b), cap(b))

    fmt.Println("===c===")
    c := append([]byte{}, buf...)
    fmt.Printf("len:%d, cap:%d\n", len(c), cap(c))

    fmt.Println("===d===")
    d := []byte{}
    fmt.Printf("len:%d, cap:%d\n", len(d), cap(d))
    for i := 0; i < len(buf); i++ {
        d = append(d, buf[i])
        fmt.Printf("len:%d, cap:%d\n", len(d), cap(d))
    }
}

Go1.2.1の結果

go version go1.2.1 windows/amd64

===a===
len:9, cap:9
===b===
len:9, cap:9
===c===
len:9, cap:9
===d===
len:0, cap:0
len:1, cap:1
len:2, cap:2
len:3, cap:4
len:4, cap:4
len:5, cap:8
len:6, cap:8
len:7, cap:8
len:8, cap:8
len:9, cap:16

Go1.3beta1の結果

go version devel +f8b50ad4cac4 Mon Apr 21 17:00:27 2014 -0700 + windows/amd64

===a===
len:9, cap:9
===b===
len:9, cap:9
===c===
len:9, cap:16
===d===
len:0, cap:0
len:1, cap:8
len:2, cap:8
len:3, cap:8
len:4, cap:8
len:5, cap:8
len:6, cap:8
len:7, cap:8
len:8, cap:8
len:9, cap:16

かんそう

realloc的な動作が減って速くなるのかな。
細かいスライスをappendで量産するようなプログラムには影響ありそう。
動作が明らかに変更されてるけど、特に資料がない気がする。英語力が低すぎて探せなかった。

8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8