[Go語言]binary tree演算法的華山論劍

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

前言

  在benchmarkgame(世界上最火的效能對比網站)上,Go語言一直有一個槽點,就是極其慢的binary tree效能,執行用時40秒 (我的機器上,16秒),與此對比,Java版本是6秒,那麼問題來了:為什麼慢得令人髮指?我們來深入研究下慢的原因,然後看看能否對其進行改進。

  對於binary tree演算法中,最耗效能的地方就是海量的node分配和bottomUpTree()遞迴函式的調用,與這兩項對應的go的特性就是gc的goroutine的堆棧分配。

GC

這個世界沒有完美的GC,任何選擇都有代價,一般來說就是低延遲和高吞吐的權衡。

問題描述

   Java採用的是分代GC,優點是node的分配非常輕量,缺點就是分代gc需要使用更多的記憶體空間,同時當對象被移動到tenured堆時,會發生大量的記憶體拷貝。

  Go的gc不是分代的,因此在node的分配上需要消耗更多的資源。Go的gc選擇了超低的延遲,同時犧牲了部分吞吐,對於絕大多數應用來說,Go的選擇是非常正確的,但是對於binary tree這種演算法來說,就不是很適合了。

解決方案

  針對GC的最佳化,有兩個通用的解決方案就是提前分配合適的堆棧空間和對象複用。對於binary tree演算法,就是Nodes的預先分配和複用。


Goroutine的堆棧

輕量的Goroutine是Go語言的靈魂所在

問題描述

  為了讓goroutine儘可能輕量,go僅僅為每個goroutine分配了2KB的初始堆棧大小,在之後Go會根據需要動態擴充堆棧大小。同樣,對於絕大多數情境,這種選擇都是非常正確的,但是針對binary tree演算法,這種選擇就有了一些問題。

  Go是在每次函數調用之前檢查goroutine的堆棧大小,如果發現當前堆棧不夠用,就會重新分配一個新的堆棧空間,然後將舊的堆棧拷貝到新的裡。這種操作開銷是很小的,但是在binary tree中,bottomUpTree()基本上不做什麼工作,調用卻是極其頻繁,這樣一來再小的開銷累積起來也會非常可觀。而且這個函數的調用是深遞迴,當堆棧需要增長時,可能會拷貝幾次,不僅僅是一次!

解決方案

  將bottomUpTree()改為非遞迴的函數,雖然不易實現,但是還是可以做到的。


新舊Binary tree實現對比

沒有對比,就沒有傷害!

舊版本代碼連結

運行用時:

 > time go run old.go 20stretch tree of depth 21     check: -12097152  trees of depth 4    check: -2097152524288   trees of depth 6    check: -524288131072   trees of depth 8    check: -13107232768    trees of depth 10   check: -327688192     trees of depth 12   check: -81922048     trees of depth 14   check: -2048512  trees of depth 16   check: -512128  trees of depth 18   check: -12832   trees of depth 20   check: -32long lived tree of depth 20  check: -1real    0m16.279suser    1m47.569ssys 0m2.663s

新版本代碼連結

運行用時

time go run new.go 20stretch tree of depth 21     check: -12097152  trees of depth 4    check: -2097152524288   trees of depth 6    check: -524288131072   trees of depth 8    check: -13107232768    trees of depth 10   check: -327688192     trees of depth 12   check: -81922048     trees of depth 14   check: -2048512  trees of depth 16   check: -512128  trees of depth 18   check: -12832   trees of depth 20   check: -32long lived tree of depth 20  check: -1dur: 1.71074946sreal    0m1.914suser    0m10.149ssys 0m0.157s


結論

  效能從16.28秒提升到了1.91秒,提升巨大!

  這裡提出的解決方案看似是針對binary tree,其實對於任何GC語言和使用情境來說都是通用的。

  牢記這兩種解決方案吧:

  • 記憶體空間預分配
  • 對象複用

聯繫我們

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