問題描述
我知道 JavaScript 有一個垃圾收集器.因此,使用delete只刪除一個對該對象的引用,當沒有對該對象的引用時,它被GC刪除.
I know that JavaScript has a garbage collector. Therefore, using delete remove only a reference to the object, and when there is no more reference to this object, it is deleted by the GC.
JavaScript 很棘手,由于閉包、模糊的命名空間和原型繼承,知道什么時候到現(xiàn)在或為什么并不總是很明顯.
JavaScript is tricky, with the closures, the fuzzy name space and the prototype inheritance, it's not always obvious to know when to now or why.
我正在編寫一個相當大的 JavaScript 項目,并希望避免內(nèi)存泄漏,同時限制全局內(nèi)存使用.我根本不在優(yōu)化階段(讓我們先讓這些東西工作:-)),但如果知道內(nèi)存管理的良好做法以避免編寫糟糕的代碼,那就太好了.
I am coding a fairly large JavaScript project and would like to avoid memory leak, while limiting the global memory usage. I am not at all in the optimizing stage (let's get the stuff work first :-)), but it would be nice to know the good practices for memory management in order to avoid writing crappy code.
- 那么我應該什么時候使用delete?
- 我應該避免哪些陷阱,使用對象?
- 關于閉包的一些知識?
- 要強調(diào)一些好的做法?
推薦答案
根據(jù)我的經(jīng)驗,垃圾收集器的實現(xiàn)好/不好取決于瀏覽器.應用良好的面向對象編程實踐是一個好的開始.
From my experience, Garbage Collectors are well/poorly implemented depending on the browser. Applying good Object Oriented programming practices is a good start.
我唯一的建議:不要通過連接 DOM 和javascript 對象(不會被 DOM 和 JS GC 清除的循環(huán)引用).這些錯誤會比您在應用程序中實例化的任何對象消耗更多的內(nèi)存.
My only advice: do not create memory leaks by connecting DOM & javascript objects (circular references that won't be cleared by DOM and JS GCs). These mistakes will eat far more memory than any object you will instantiate within your application.
有關 DOM/JS 內(nèi)存泄漏的更多詳細信息.http://msdn.microsoft.com/en-us/library/bb250448%28VS.85%29.aspx
More details on DOM/JS memory leaks. http://msdn.microsoft.com/en-us/library/bb250448%28VS.85%29.aspx
這篇關于JavaScript 內(nèi)存管理的陷阱?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!