LoginSignup
1
1

More than 5 years have passed since last update.

[golang]sliceの容量確保あり/なしの速度比較

Last updated at Posted at 2017-04-15

検証コード

package main

import (
    "fmt"
    "time"
)

func main() {
    // 容量未定義
    s1 := make([]int, 1)
    // 容量定義
    s2 := make([]int, 1, 100000000)

    var (
        start time.Time
        end   time.Time
    )

    // 容量未定義の速度
    start = time.Now()
    for i := 1; i < cap(s2); i++ {
        s1 = append(s1, i)
    }
    end = time.Now()
    fmt.Printf("容量未定義:%fsec\r\n", end.Sub(start).Seconds())

    // 容量定義済みの速度
    start = time.Now()
    for j := 1; j < cap(s2); j++ {
        s2 = append(s2, j)
    }
    end = time.Now()
    fmt.Printf("容量定義済:%fsec\r\n", end.Sub(start).Seconds())
}

結果(念のため3回)

容量未定義:1.138697sec
容量定義済:0.381012sec
容量未定義:1.216133sec
容量定義済:0.535423sec
容量未定義:1.184637sec
容量定義済:0.352957sec
1
1
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
1
1