Golang 最佳化之路——空結構

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

寫在前面

開發 hashset 常用的套路:

map[int]int8map[int]bool

我們一般只用 map 的鍵來儲存資料,值是沒有用的。所以來緩衝集合資料會造成記憶體浪費。

Null 物件

Null 物件是個神奇的東西。它指的是沒有欄位的結構類型。

type Q struct{}

它牛逼的地方在於:

  • 可以和普通結構一樣操作

    var a = []struct{}{struct{}{}}fmt.Println(len(a)) // prints 1
  • 不佔用空間

    var s struct{}fmt.Println(unsafe.Sizeof(s)) // prints 0
  • 聲明兩個Null 物件,它們指向同一個地址

    type A struct{}a := A{}b := A{}fmt.Println(&a == &b) // prints true

造成這個結果的原因是 Golang 的編譯器會把這種Null 物件都當成runtime.zerobase處理。

var zerobase uintptr

hashset

有了上面的介紹,就可以利用空結構來最佳化 hashset 了。

var itemExists = struct{}{}type Set struct {    items map[interface{}]struct{}}func New() *Set {    return &Set{items: make(map[interface{}]struct{})}}func (set *Set) Add(item interface{}) {    set.items[item] = itemExists}func (set *Set) Remove(item interface{}) {    delete(set.items, item)}func (set *Set) Contains(item interface{}) bool {    if _, contains := set.items[item]; !contains {        return false    }    return true}

一個簡易的 hashset 實現就完成了。

效能比較

func BenchmarkIntSet(b *testing.B) {    var B = NewIntSet(3)    B.Set(10).Set(11)    for i := 0; i < b.N; i++ {        if B.Exists(1) {        }        if B.Exists(11) {        }        if B.Exists(1000000) {        }    }}func BenchmarkMap(b *testing.B) {    var B = make(map[int]int8, 3)    B[10] = 1    B[11] = 1    for i := 0; i < b.N; i++ {        if _, exists := B[1]; exists {        }        if _, exists := B[11]; exists {        }        if _, exists := B[1000000]; exists {        }    }}BenchmarkIntSet-2       50000000                35.3 ns/op             0 B/op          0 allocs/opBenchmarkMap-2          30000000                41.2 ns/op             0 B/op          0 allocs/op

結論

  • 效能,有些提升,但不是特別明顯。尤其是線上壓力不大的情況效能應該不會有明顯變化;

  • 記憶體佔用。我們的服務緩衝較多、佔用記憶體較大,通過這個最佳化實測可以減少 1.6 GB 的空間。不過這個最佳化的空間取決於資料量。

參考文獻

  • 【1】The empty struct - Dave Cheney

  • 【2】gods - emirpasic

  • 【3】 《Go 語言學習筆記》 - 雨痕。5.5 結構。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.