golang slice效能分析

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

golang在gc這塊的做得比較弱,頻繁地申請和釋放記憶體會消耗很多的資源。另外slice使用數組實現,有一個容量和長度的問題,當slice的容量用完再繼續添加元素時需要擴容,而這個擴容會把申請新的空間,把老的內容複寫到新的空間,這是一個非常耗時的操作。有兩種方式可以減少這個問題帶來的效能開銷:

  1. 在slice初始化的時候設定capacity(但更多的時候我們可能並不知道capacity的大小)
  2. 複用slice

下面就針對這兩個最佳化設計了如下的benchmark,代碼在: https://github.com/hatlonely/...

BenchmarkAppendWithoutCapacity-8                     100      21442390 ns/opBenchmarkAppendWithCapLessLen10th-8                  100      18579700 ns/opBenchmarkAppendWithCapLessLen3th-8                   100      13867060 ns/opBenchmarkAppendWithCapEqualLen-8                     200       6287940 ns/opBenchmarkAppendWithCapGreaterLen10th-8               100      18692880 ns/opBenchmarkAppendWithoutCapacityReuse-8                300       5014320 ns/opBenchmarkAppendWithCapEqualLenReuse-8                300       4821420 ns/opBenchmarkAppendWithCapGreaterLen10thReuse-8          300       4903230 ns/op

主要結論:

  1. 在已知 capacity 的情況下,直接設定 capacity 減少記憶體的重新分配,有效提高效能
  2. capacity < length,capacity越接近length,效能越好
  3. capacity > lenght,如果太大,反而會造成效能下降,這裡當capacity > 10 * length時,與不設定capacity的效能差不太多
  4. 多次使用複用同一塊記憶體能有效提高效能

轉載請註明出處
本文連結:http://hatlonely.github.io/20...

聯繫我們

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