Conversation
| // GC対象にするため参照を外す | ||
| nodesToVisit[topIndex].node = nil |
There was a problem hiding this comment.
こういう小技もあるのですね。勉強になります。
ちなみに、ここで参照を外さなくても、この関数を抜けたらGCは走りますよね…?
There was a problem hiding this comment.
これよく知らなかったのですが、ここの SliceTricks で推奨されていました。
https://go.dev/wiki/SliceTricks
NOTE If the type of the element is a pointer or a struct with pointer fields, which need to be garbage collected, the above implementations of Cut and Delete have a potential memory leak problem: some elements with values are still referenced by slice a’s underlying array, just not “visible” in the slice. Because the “deleted” value is referenced in the underlying array, the deleted value is still “reachable” during GC, even though the value cannot be referenced by your code. If the underlying array is long-lived, this represents a leak. The following code can fix this problem:
There was a problem hiding this comment.
おっしゃるとおりで、この関数抜けたら問題なく走るはずなので、状況によっては使ってもいいということかと思います。
There was a problem hiding this comment.
コメントありがとうございます。
はい、 maxDepth から戻ったら nodesToVisit が参照されなくなるためGC対象となると思います。
手癖で書いていた側面もあるので、必要かどうか考えた上で nil 代入するかどうか考えるようにします。
生存期間が長くない、そもそもサイズ的に問題にならないなどの場合はなくてもいいと思いました。
(実務ではガイドラインに従います)
今回の問題
Maximum Depth of Binary Tree - LeetCode
使用言語
Go
次に解く問題
Minimum Depth of Binary Tree - LeetCode