Javascript 和垃圾收集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18800440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript and Garbage collection
提问by Ed Heal
Is there any way to control when Javascript performs garbage collection? I would like to enable it to perform garbage collection at certain times to ensure the smooth operation of my web site
有什么方法可以控制 Javascript 何时执行垃圾收集?我想启用它在特定时间执行垃圾收集,以确保我的网站顺利运行
回答by Shadow
Javascript doesn't have explicit memory management, it's the browser which decides when to clean it up. Sometimes it may happen that you experience un-smooth rendering of JavaScript due to a garbage collection pause.
Javascript 没有明确的内存管理,它是浏览器决定何时清理它。有时,由于垃圾收集暂停,您可能会遇到 JavaScript 渲染不流畅的情况。
There are many techniques that you can apply to overcome glitches caused by garbage collection (GC). More you apply more you explore. Suppose you have a game written in JavaScript , and every second you are creating a new object then its obvious that at after certain amount of time GC will occur to make further space for your application.
您可以应用许多技术来克服垃圾回收 (GC) 引起的故障。你应用的越多,探索的越多。假设你有一个用 JavaScript 编写的游戏,你每一秒都在创建一个新对象,那么很明显,在一定的时间后,GC 会发生,为你的应用程序腾出更多空间。
For real time application like games, which requires lot of space the simplest thing you can do is to reuse the same memory. It depends on you how you structure your code. If it generates lots of garbage then it might give choppy experience.
对于像游戏这样需要大量空间的实时应用程序,您可以做的最简单的事情就是重用相同的内存。这取决于您如何构建代码。如果它产生大量垃圾,那么它可能会带来断断续续的体验。
By using simple procedures:This is well know that new keyword indicates allocation. Wherever possible you can try to reuse the same object by each time by adding or modifying properties. This is also called recycling of object
通过使用简单的程序:众所周知,new 关键字表示分配。只要有可能,您可以尝试通过添加或修改属性,每次都重用同一个对象。这也称为对象的回收
In case of Arrays, assigning [] is often used to clear array, but you should keep in mind that it also creates a new array and garbages the old one. To reuse the same block you should use arr.length = 0
This has the same effect but it reuses the same array object instead of creating new one.
在 Arrays 的情况下,赋值 [] 通常用于清除数组,但您应该记住,它还会创建一个新数组并清除旧数组。要重用相同的块,您应该使用arr.length = 0
它具有相同的效果,但它重用相同的数组对象而不是创建新对象。
In case of functions: Sometimes our program needed to call a specific function more time or on certain intervals by using setInterval or setTimeout.
在函数的情况下:有时我们的程序需要通过使用 setInterval 或 setTimeout 来更多时间或以特定间隔调用特定函数。
ex: setTimeout(function() { doSomething() }, 10);
You can optimize the above code by assigning the function to a permanent variable rather than spawning each time at regular intervals.
您可以通过将函数分配给永久变量而不是每次定期生成来优化上述代码。
ex : var myfunc = function() { doSomething() }
setTimeout(myfunc, 10);
Other possible thing is that, the array slice() method returns a new array (based on a range in the original array,that can remain untouched), string's substr also returns a new string (based on a range of characters in the original string, that can remain untouched), and so on. Calling these functions creates garbage if not reutilized properly.
另一个可能的事情是,数组 slice() 方法返回一个新数组(基于原始数组中的范围,可以保持不变),字符串的 substr 也返回一个新字符串(基于原始字符串中的字符范围,可以保持不变),依此类推。如果没有正确重用,调用这些函数会产生垃圾。
To avoid garbage completely in JavaScript is very difficult, you could say impossible. Its depends, how you reuse the objects and variables to avoid garbage. If your code is well structured and optimized you can minimize the overhead.
在 JavaScript 中完全避免垃圾是非常困难的,可以说是不可能的。这取决于您如何重用对象和变量以避免垃圾。如果您的代码结构良好且经过优化,则可以最大限度地减少开销。
回答by DevlshOne
Unfortunately, there is no way to control WHEN the garbage collection takes place but with the proper formation of objects, you CAN control how quickly and cleanly it happens. Take a look at these documents on Mozilla Dev Net.
不幸的是,没有办法控制垃圾收集何时发生,但是通过正确形成对象,您可以控制它发生的速度和干净程度。查看Mozilla Dev Net上的这些文档。
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.
该算法假设知道一组称为根的对象(在 JavaScript 中,根是全局对象)。垃圾收集器会周期性地从这些根开始,找到从这些根引用的所有对象,然后从这些根引用的所有对象,等等。从根开始,垃圾收集器将因此找到所有可达的对象并收集所有非可达对象。
该算法比前一个算法更好,因为“对象具有零引用”导致该对象无法访问。正如我们在循环中看到的那样,情况并非如此。
回答by Paul S.
Why not keep references to all your objects until you want them to be GC'd?
为什么不保留对所有对象的引用,直到您希望它们被 GC 处理?
var delayed_gc_objects = [];
function delayGC(obj) { // keeps reference alive
return delayed_gc_objects[delayed_gc_objects.length] = obj;
}
function resumeGC() { // kills references, letting them be GCd
delayed_gc_objects.length = 0;
}
回答by Jean Carlos
you can perform some changes to improve your memory use, like:
您可以执行一些更改以改善内存使用,例如:
- don't set variables on loops
- avoid using of global variables and functions. they will take a piece of memory until you get out
- 不要在循环上设置变量
- 避免使用全局变量和函数。他们会带走一段记忆直到你出去
回答by anish
JavaScript is a garbage-collected language, meaning that the execution environment is responsible for managing the memory required during code execution. The most popular form of garbage collection for JavaScript is called mark-and-sweep. A second, less-popular type of garbage collection is reference counting. The idea is that every value keeps track of how many references are made to it
JavaScript 是一种垃圾收集语言,这意味着执行环境负责管理代码执行期间所需的内存。JavaScript 最流行的垃圾收集形式称为标记和清除。第二种不太流行的垃圾收集类型是引用计数。这个想法是每个值都会跟踪对其进行了多少引用
GC follows these algo, even if you manage to trigger the GC, it will not be guaranteed that it will run immediately, you are only marking it
GC遵循这些算法,即使你设法触发GC,也不能保证它会立即运行,你只是标记它
回答by Ahmed Gaber - Biga
garbage collection (GC) is a form of automatic memory management by removing the objects that no needed anymore.
垃圾回收 (GC) 是一种通过删除不再需要的对象来进行自动内存管理的形式。
any process deal with memory follow these steps:
任何处理内存的进程都遵循以下步骤:
1 - allocate your memory space you need
1 - 分配你需要的内存空间
2 - do some processing
2 - 做一些处理
3 - free this memory space
3 - 释放此内存空间
there are two main algorithm used to detect which objects no needed anymore.
有两种主要算法用于检测不再需要的对象。
Reference-counting garbage collection: this algorithm reduces the definition of "an object is not needed anymore" to "an object has no other object referencing to it", the object will removed if no reference point to it
引用计数垃圾收集:该算法将“不再需要一个对象”的定义简化为“一个对象没有其他对象引用它”,如果没有引用指向它,该对象将被删除
Mark-and-sweep algorithm: connect each objects to root source. any object doesn't connect to root or other object. this object will be removed.
标记和清除算法:将每个对象连接到根源。任何对象都不会连接到根或其他对象。此对象将被删除。
currently most modern browsers using the second algorithm.
目前大多数现代浏览器都使用第二种算法。