Open
Conversation
oda
reviewed
Oct 5, 2024
| - キャパシティを設定することにより、スライスがキャパシティオーバーでリロケートされるのを防ぐことができ、特に綺麗な形をした二分木に対して効果を発揮できる | ||
| - 実験:step1のコードとローカルで実行時間の差を計測 | ||
| - 1. 深さ17、ノード数2^17の綺麗な二分木(常に子が2ついる) | ||
| - 見積もり実行時間:2^17 / 10e8 ≒ 10e5 / 10e8 = 10e-3 = 1ms |
Owner
Author
There was a problem hiding this comment.
|
拡張率のところは、償却計算量の概念などを聞かれることがあります。
|
Owner
Author
|
#21 (comment) を受けて
こんな感じ? |
|
はい、それで OK です。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
問題:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
Go: スライスのキャパシティ
2dでスライスのキャパシティについて考察したら、キャパシティの増え方について知りたくなった。
前提として、Goのスライスは基底配列(underlying array)へのポインタ、要素数、キャパシティの3つのプロパティを保持する。
初期のキャパシティは、指定されていればその値、指定されていなければ要素数に等しい。appendがあると、キャパシティを拡張する必要ができる。このとき、要素数1024までは大体2倍に拡張され、それ以上になると少し拡張率が下がって1.25~1.5倍くらいになる。拡張率に関しては、スライスの型によるばらつきが多少ある。
キャパシティを拡大するときに内部では、1. 新しいキャパシティを決める、2. 新しい基底配列のメモリ領域を確保、3. 元のスライスの要素を新しい基底配列にコピー。以下のコードで新しいメモリ領域に基底配列が割り当てられている様子がわかる(これを観察したかったことが当初の動機)
結論
スライスのメモリ領域の再割り当て(再ハッシュみたいな言い方ないのかな?)があるとその分の時間がかかるし、ガベージコレクションが起きるので、パフォーマンスが落ちる。なので、最大要素数がわかるならキャパシティは初期化時に決めておこう
参考:Sliceのcapacityはどのように増加していくか