gf架構之並發安全容器 - gmap,以及與sync.Map的效能比較

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

gf架構提供了幾個非常實用的並發安全容器,其中gmap就是項目開發中最常用的一個。

gmap具體的方法請參考godoc:https://godoc.org/github.com/...

gmap內部有多個類型結構體定義,包括:IntBoolMap、IntIntMap、IntInterfaceMap、IntStringMap、InterfaceInterfaceMap、StringBoolMap、StringIntMap、StringInterfaceMap、StringStringMap、UintInterfaceMap。

從執行效率上考慮,基於不同的需求情境,選擇合適的類型結構體,其執行效率是不一樣的,以下使用基準測試來對比各個類型的寫入效能(測試代碼):

john@johnstation:~/Workspace/Go/GOPATH/src/gitee.com/johng/gf/g/container/gmap$ go test gmap_test.go -bench=".*"goos: linuxgoarch: amd64BenchmarkIntBoolMap_Set-8                  10000000           171 ns/opBenchmarkIntIntMap_Set-8                   10000000           181 ns/opBenchmarkIntInterfaceMap_Set-8             10000000           227 ns/opBenchmarkIntStringMap_Set-8                10000000           271 ns/opBenchmarkInterfaceInterfaceMap_Set-8        5000000           331 ns/opBenchmarkStringBoolMap_Set-8                5000000           271 ns/opBenchmarkStringIntMap_Set-8                 5000000           300 ns/opBenchmarkStringInterfaceMap_Set-8           5000000           363 ns/opBenchmarkStringStringMap_Set-8              5000000           394 ns/opBenchmarkUintInterfaceMap_Set-8            10000000           275 ns/opPASSok      command-line-arguments    37.024s

此外,需要說明的是,go語言從1.9版本開始引入了同樣支援並發安全的sync.Map,我們來看看基準測試結果怎麼樣:

john@johnstation:~/Workspace/Go/GOPATH/src/gitee.com/johng/gf/g/container/gmap$ go test *.go -bench=".*"goos: linuxgoarch: amd64BenchmarkGmapSet-8            10000000           181 ns/opBenchmarkSyncmapSet-8          5000000           366 ns/opBenchmarkGmapGet-8            30000000            82.6 ns/opBenchmarkSyncmapGet-8         20000000            95.7 ns/opBenchmarkGmapRemove-8         20000000            69.8 ns/opBenchmarkSyncmapRmove-8       20000000            93.6 ns/opPASSok      command-line-arguments    27.950s

查看sync.Map的原始碼我們可以發現,其實現原理類似於gmap.InterfaceInterfaceMap這個類型結構體,但是效率卻沒有gmap.InterfaceInterfaceMap高。

因此可以發現,支援並發安全的gmap包的效率已經相當地高。

聯繫我們

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