Say I instantiate a large object with var and new. After I'm done with it, can I "free" it by setting it to null? Is this something Javascript GCs look for?
The garbage collection is interested in objects, that are not referenced by ANY other object. So make sure there are no references left anywhere in your application (Arrays etc.)
You can break the reference by setting the variable to null, but it doesn't break any other references.
All references need to be broken individually before the object can be GC'd.
So yes, if the only reference to the object that is held by that variable, then setting it to null will free it for eventual GC.
as am not i am stated, you'll need to break all references in order for a variable to be eligible for garbage collection. This can be a difficult task if you can't track down that last reference to a specific Object, so use the tools available to you for this task. Personally I use the Chrome's Heap Profiler which you can read about in the chrome docs.
Also, note that only non-primitive types are passed by reference (and therefore only non-primitive types can be GC'd).
Related
In Javascript I'm iterating through an array of UNIDs and getting a NotesDocument by UNID, then I do a doc.remove(true);
having done that is it necessary to do a doc.recycle()?
Short answer is yes.
For newbies, Notes objects in Java consist of a Java object and a reference to a C++ object. So when you a Java object becomes null (or useless), garbage collector will clear the memory space after a certain amount of time. However, the C++ handle will persist. So we are recycling notes objects to destroy C++ object references. This page has a good explanation abouyt recycling.
On the other hand, doc.remove() can be thought as a state change. Moreover, if soft deletion is enabled in your database, it won't even remove the document, will just mark as deleted (you have to call .removePermanently() to hard-delete it). The C++ object reference will stay in the memory.
Therefore, remove method will not trigger a recycle for the object. Recycle is only triggerred by the object itself or its parent.
I believe you should still recycle it. It's an object at that point not a document.
Do we need to unset variables in JavaScript, and why?
For example in PHP it's recommended to unset all temporary variables in all kind of loops to keep memory free and avoid variables duplicates.
But anyways according to php - what's the benefit of unsetting variables? question:
Is it true that unsetting variables doesn't actually decrease the memory consumption during runtime?
-Yep.
So should we delete window.some_var;?
Or we should use some_var = null?
Or we should not unset variables to avoid additional CPU cycles?
UPD:
Related questions:
How to unset a Javascript variable?
How to remove a property from a javascript object
No, plus in some cases you can't delete variables in the global scope. Variables that are properly declared using the var keyword cannot be deleted (implied global variables can be deleted, on the other hand. Always use the var keyword to declare variables).
Also, javascript engines have this thing called garbage collector that automatically looks for variables that are no longer used or referenced somewhere when your code is 'running'. Once it finds one, it'll shove it off immediately into the Abyss (deletes the variable in the memory)
No, it is not necessary to delete variables when you’re done with them. If you have so many enormous, global variables that this is actually a problem, you need to rethink your design.
And yes, it’s also silly in PHP, and no, it has nothing to do with avoiding “additional CPU cycles”.
Specifically:
“Unsetting temporary variables in loops”
They’re temporary, and probably either a) integers or b) references that take up about as much space as an integer. Don’t bother.
“Avoiding duplicate variables”
Again – references. Setting things that are still referenced elsewhere to null is pointless.
If you feel like it’s clutter, that is a good sign that more things should be going out of scope (i.e. use more functions).
In most other cases that you haven’t mentioned, the engine is also smart enough to manage your stuff properly. Do not optimize prematurely.
David Flanagan answers this quite nicely in his book, JavaScript: The Definitive Guide:
The JavaScript interpreter performs automatic garbage collection for memory management. This means that a program can create objects as needed, and the programmer never needs to worry about destruction or deallocation of those objects. When an object is no longer reachable – when a program no longer has any way to refer to it – the interpreter knows it can never be used again and automatically reclaims the memory it was occupying.
This doesn't mean that memory leaks can't happen in JavaScript. Far from it. Circular (or cyclic) references are a frequent problem in browsers which implement reference counting, as documented here by IBM:
A circular reference is formed when two objects reference each other, giving each object a reference count of 1. In a purely garbage collected system, a circular reference is not a problem: If neither of the objects involved is referenced by any other object, then both are garbage collected. In a reference counting system, however, neither of the objects can be destroyed, because the reference count never reaches zero. In a hybrid system, where both garbage collection and reference counting are being used, leaks occur because the system fails to identify a circular reference. In this case, neither the DOM object nor the JavaScript object is destroyed. Listing 1 shows a circular reference between a JavaScript object and a DOM object.
If you're worried that your website contains a JavaScript memory leak, Google has a tool, aptly named "Leak Finder for JavaScript", which can help you find the cause.
Further reading: What is JavaScript garbage collection?
I am developing an Android game using JS framework. I want to make sure that some of the objects are garbage collected once I am done using them. How do i force it? Should I use null or undefined?
You can't force garbage collection (not in any sane fashion).
If your variables aren't going out of scope automatically, just set them to null.
Best advice is to define them in scope that makes them eligible for garbage collection. This means don't use global variables that never become eligible for collection. Instead declare them as locals.
You could set it to null, and if that is then the last reference to that object, it will become eligible for garbage collection.
http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/
TGH's suggestion is the best though, I'd recommend that.
If you want force garbage collection on a variable in Javascript, is it better to set it as null or undefined?
Doesn't matter, you can even set it to another object you created: as long as the object originally referenced by the variable is no longer referenced anywhere, it can be garbage collected. Think of your object as "something being referenced by variables".
If no variables reference it, it can be garbage collected, and "putting another object into a variable" will make the variable no longer reference the previous object.
I want to make sure that some of the objects are garbage collected once I am done using them. How do i force it?
You can force major garbage collection to be triggered in a Node-based runtime (e.g. Electron or NW.js), by using the --expose-gc flag and running:
global.gc();
If your app/game is browser-based, in Chrome only you can use the --allow-natives-syntax switch (your users would need to pass this to Chrome themselves), and call:
%CollectGarbage();
Note: dead simple, but you might as well just do a window.location.reload() as a fallback, if you can easily continue from where you left off (e.g. reload the game into another level, if you will).
Remember, however, these calls won't screw around, and can block for whole seconds if there is a lot of garbage to collect. This can be ideal if you have determined pauses in your game, such as loading screens between levels, but tricky otherwise.
You might also want to consider using an object pool, with or without using manual garbage collection, to simply reduce garbage and improve performance.
var Obj = function(){}; var X = new Obj();
will X = null properly clear memory?
Also would this be equivalent?
var Obj = function(){};
var X = {};
X.obj = new Obj();
delete(X.obj);
EDIT
It would seem that although deleting X.obj would NOT immediately clear memory, it would help the garbage collection. If I don't delete X.obj, there would still be a pointer to an object and so the GC may not clean it up.
Although I'm picking #delnan's answer, if you're reading this you should def also catch Benubird's article.
I also notice I accidentally wrote delete(X) originally instead of delete(X.obj) - sorry.
The short answer is that you don't. delete simply removes a reference (and not in the way you try to use it, see the above link - delete is one of those language features few people actually understand), nothing more. The implementation clears memory for you, but it's not your business when (and even if, strictly speaking - this is why one shouldn't rely on finalizers in GC'd languages that offer them) it does. Note though:
Only objects that can be proven to be unreachable (i.e. no way to access it) to all code can be removed. What keeps references to whom is usually fairly obvious, as least conceptually. You just need to watch out when dealing with lots of closures, as they may capture more variables than you think. Also note that circular references are cleaned up properly.
There's a bug in old (but sadly still used) IE versions involving garbage collection of JS event handlers and DOM elements. Google (perhaps even SO) should have better material on my memory.
On the plus side, that means you won't get dangling pointer bugs or (save of course the aforementioned pitfalls) memory leaks.
No, that will not clear memory.
Read this:
http://perfectionkills.com/understanding-delete/
No - Javascript runs GC when it feels like it.
The Delete method only deletes the reference - not the object. Any other references would be left out in the open waiting for the garbage collector.
JavaScript has its own GC, and it will run around and clean things up when nothing refers to them anymore.
I still think it's a good practice to null objects.
Deleteing an object also helps the GC because it will see something dangling, and say "I'm going to eat you because you're all alone (and now some cynical laugh)".
You should look at Deleting Objects in JavaScript
Even though there's a GC, you still want to ensure your script is optimized for performance as peoples computers, browsers, and fricken toolbars (and the number of them), will vary.
Generally speaking, memory management in Javascript is user-agent-specific. The basics of the garbage collector are through reference-counting. So, by setting a reference to null (using the delete keyword or by explicit assignment), you can assure yourself that a reference will be cleaned up, IF the object does not have any references that will live outside of its creation scope. That being the case, the GC will have already cleaned up any objects or variables whose scope has ended without your explicitly setting it to null.
There are some things to take care of, though - circular references are easy to create in JS, especially between a DOM element and an object. Care must be taken to clear (or not create in the first place) references to and/or from DOM elements within objects. If you do create a to/from reference related to DOM, be sure to explicitly clean them up by setting the references to null - both on your object and on the DOM element. Simply setting a parent object to null is not sufficient if there are child objects with references to/from DOM or localStorage because those references will live on, and if there was any reference from the child to the parent, then the parent will live on in memory because of that reference.
Web pages can actually leak trash in your memory this way - after you navigate away, the circular references keep objects and DOM elements in memory until you've restarted the browser!
An article on the subject: http://docstore.mik.ua/orelly/webprog/jscript/ch11_03.htm, and another detailed look: http://blogs.msdn.com/b/ericlippert/archive/2003/09/17/53038.aspx
JavaScript memory is generally handled similarly to Java - I mean there is (or there should be) a garbage collector which would delete the object if there is no references to it. So yes, simply "nullifying " the reference is the only way you should "handle" freeing memory, and the real freeing is the JS host part.
For example, I have this code:
{a: 42}
After this line was executed, I think the object is stored somehow in the memory, I'm wondering how can I get it, in some tricky way?
No.
You can't do this.
Any decent js interpreter will destroy it with the garbage collector.
No: once you lose all references to an object, you cannot recover it and the GC will collect it.
No.
Anonymous objects are intended to work this way. If you need to retrieve an object later on, you should simply name it. (I assume you are asking this question out of curiosity and not out of neccessity).
As soon as an object has no existing references to it, the garbage collector should destroy the object, as is confirmed by this page:
ECMAScript uses automatic garbage
collection. The specification does not
define the details, leaving that to
the implementers to sort out, and some
implementations are known to give a
very low priority to their garbage
collection operations. But the general
idea is that if an object becomes
un-referable (by having no remaining
references to it left accessible to
executing code) it becomes available
for garbage collection and will at
some future point be destroyed and any
resources it is consuming freed and
returned to the system for re-use.
This would normally be the case upon
exiting an execution context. The
scope chain structure, the
Activation/Variable object and any
objects created within the execution
context, including function objects,
would no longer be accessible and so
would become available for garbage
collection.