14 - GC 友好

2020-07-15  本文已影响0人  天命_风流

尽量比避免内存开销

package gc_friendly

import (
    "testing"
)

const NumOfElems = 1000

type Content struct {
    Detail [10000]int
}

func withValue(arr [NumOfElems]Content) int {
    //  fmt.Println(&arr[2])
    return 0
}

func withReference(arr *[NumOfElems]Content) int {
    //b := *arr
    //  fmt.Println(&arr[2])
    return 0
}

func TestFn(t *testing.T) {
    var arr [NumOfElems]Content
    //fmt.Println(&arr[2])
    withValue(arr)
    withReference(&arr)
}

func BenchmarkPassingArrayWithValue(b *testing.B) {
    var arr [NumOfElems]Content

    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        withValue(arr)
    }
    b.StopTimer()
}

func BenchmarkPassingArrayWithRef(b *testing.B) {
    var arr [NumOfElems]Content

    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        withReference(&arr)
    }
    b.StopTimer()
}

初始化合适的切片大小

image.png
package gc_friendly

import "testing"

const numOfElems = 100000
const times = 1000

func TestAutoGrow(t *testing.T) {
    for i := 0; i < times; i++ {
        s := []int{}
        for j := 0; j < numOfElems; j++ {
            s = append(s, j)
        }
    }
}

func TestProperInit(t *testing.T) {
    for i := 0; i < times; i++ {
        s := make([]int, 0, 100000)
        for j := 0; j < numOfElems; j++ {
            s = append(s, j)
        }
    }
}

func TestOverSizeInit(t *testing.T) {
    for i := 0; i < times; i++ {
        s := make([]int, 0, 800000)
        for j := 0; j < numOfElems; j++ {
            s = append(s, j)
        }
    }
}

func BenchmarkAutoGrow(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := []int{}
        for j := 0; j < numOfElems; j++ {
            s = append(s, j)
        }
    }
}

func BenchmarkProperInit(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := make([]int, 0, numOfElems)
        for j := 0; j < numOfElems; j++ {
            s = append(s, j)
        }
    }
}

func BenchmarkOverSizeInit(b *testing.B) {
    for i := 0; i < b.N; i++ {
        s := make([]int, 0, numOfElems*8)
        for j := 0; j < numOfElems; j++ {
            s = append(s, j)
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读