メモリリーク

メモリリークに関して理解したかったので、いくつか記事を読んでみた。

ガーベッジ・コレクターは定期的にオブジェクト・グラフ全体を調べ、各オブジェクトを参照している他のオブジェクトの数をカウントします。あるオブジェクトのカウントがゼロの場合 (そのオブジェクトを参照している他のオブジェクトがない場合)、またはそのオブジェクトに対する唯一の参照が循環参照の場合には、そのオブジェクトのメモリーを回収することができます。

http://www.ibm.com/developerworks/jp/web/library/wa-jsmemory/

This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".

This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

This algorithm is better than the previous one since "an object has zero reference" leads to this object being unreachable. The opposite is not true as we have seen with cycles.

As of 2012, all modern browsers ship a mark-and-sweep garbage-collector.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management

リークするケース

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management にあるサンプルをjQuery使わないで書いてみた。

leak 変数を null にしてるからokなように見えて、onIntervalからずっと参照され続けてしまう。

リークを避ける

http://www.ibm.com/developerworks/web/library/wa-memleak/ の Avoiding memory leaks に メモリリークを避ける方法が書かれている。