Can jquery proxy be used to avoid closure memory leak? - javascript

I was reading Google's Javascript style guide regarding closure (http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Closures) and I wonder whether it is safe to use jquery proxy to execute a callback while not fall into the memory leak trap?

The thing to remember about closures in any managed memory environment is how the garbage collector works. It starts with root objects like "window" and follows every possible memory reference. If it can find an object, then that object can't be reclaimed.
The key is to cut all possible paths when you no longer need the closure. That includes the closure-referencing function, all objects that reference the function, and the object that owns the function. That would include any proxies; null out references to those as well.

Related

What is the use of cyclic reference in javascript

I was wondering despite of memory leak, what is the use of a circular reference in javascript? Even window object in the browser is circular referenced like window.window.window ...... Why we are using it and where we can use it. What are the good parts of it?
I was wondering despite of memory leak,
There is no memory leak, two objects that reference each other but are not linked anywhere else get garbage collected. The window object will never be collected, so it doesn't matter here nevertheless.
what is the use of a circular reference in javascript?
Like in any other language they can be used for various structures, such as trees (parent <-> child), linked lists (left <-> right) and many-to-many relationships (students <-> classes). Not having them would complicate some forms of traversal and would make programs significantly slower.
Why is window.window a circular reference?
window is not only an object, but it is also the most global scope where all variables are finally looked up. When you use any global variable, such as setTimeout, it gets looked up in the global scope, and therefore the window object.
window.setTimeout === /*window.*/setTimeout
Now if you want to refer to the global object, it has to be looked up in the global scope, which is itself the global object.
window.window === /*window.*/window
Therefore just the window already accesses the circular reference, it is the reason why the global object can be found at all. Otherwise window would have to be a reserved keyword.
see this page, great reasons are there
Why window.window property exists?
The point of having the window property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you'd have to do a manual var window = this; assignment at the top of your script.
Another reason, is that without this property you wouldn't be able to write, for example, "window.open('http://google.com/')". You'd have to use "open('http://google.com/')" instead.
.
and see this answer also
https://stackoverflow.com/a/35788599/1475257

What methods are there to prevent the Javascript gc from running as little as possible?

I'm learning Javascript, and in the various texts the authors will speak of javascript using a mark and sweep gc to deallocate objects from memory. They will also speak of how if you set the value a variable references to null it will delete the reference to that value, allowing the allocated space to be set for gc. This SO answer says that you can remove the allocated memory and the reference by setting the value the variable contains to null and then to undefined, effectively removing the allocated space from the heap (if I understood it correctly).
So my question is this: Is it possible to write javascript in such a way that you can eliminate gc?
(If it is implementation specific I would like to know if it is possible on v8, though if this is possible on rhino or other js implementations that would be of immense use too)
Judging by projects like LLJS my request isn't too unreasonable, but I'm not entirely sure how the memory module does it.
I've always found it helpful if I explain why I'm asking so here it goes. I really like compilers, and I wanted to write a compile-to-js language that leveraged a static inferred typing system similar to SML. The reason why I wanted to write my own was because I wanted to utilize region inference to determine exactly when objects and variables come out of scope (as much as possible) and upon leaving scope remove it from the heap, thereby eliminating as much gc as possible. This is mostly a research project (read: because I can) so any resources on memory optimization in javascript would also be greatly appreciated!
EDIT: I guess another way to phrase it would be "Is it possible to write js in such a way that the gc will deterministically never run (as much as possible)? If so what techniques would be involved?"
I'm not looking per se for delete because that marks the element for deletion thereby invoking what I wanted to (try to) avoid, I was curious if the implementation's gc would run if I removed all references (and the value) associated with the variable.
Alternatively, paraphrasing from the referenced SO Answer:
x = foo;
x = null;
x;
Is x still on the heap?
It's not entirely clear what you're looking for.
The standard Javascript implementations have NO way of manually deallocating memory. You can remove a property with the delete operator, but that just removes the property from the object. It doesn't even free any contents that the property points to (that is left for garbage collection if there are no other references to that data).
Javascript was designed from the ground up to be a garbage collected language. It frees things from physical memory only when the garbage collector runs and that garbage collector finds objects that are unreachable (e.g. there are no references to those objects still in use). The language does not contain commands to free memory.
It is possible (in some JS implementations) to call the GC yourself rather than wait for the JS engine to run it, but it's still using GC to decide what to free.
Responding to the additional things you added to your answer.
To the best I know, javascript only cleans things up when the GC runs. Until then objects are marked such that the GC can see that there are no references to them anywhere, but they aren't actually freed until the GC checks and notices this. Further, local variables in a function scope are themselves a type of object and those are not freed until the GC runs and notices that there are no references to the function scope (in JS, a closure can maintain a reference to a function scope even after the function has completed).
So, in your code example:
x = foo; x = null; x;
x is still alive and occupying some space because it's still in scope and code could still reach it. It's contents will be null which presumably takes no extra space beyond the variable itself, but the space for the variable itself won't be freed until the function context it is in is found to be reference free by the garbage collector.
JS is a garbage collected language. That's when things are actually freed from the heap. There are no instructions in the language to free things anytime sooner.
The delete keyword will trigger garbage collection by the browser. Be aware that it deletes entire chains of objects unless you nullify object references.
var o = {...};
delete o;

Finalizers for JavaScript objects

Suppose I have some asm.js code, probably created by emscripten. Suppose it has some kind of rather large heap allocated structure, which gets returned by a asm.js function as a pointer that is picked up by some JavaScript library to be wrapped in a nice JavaScript object. Fine so far.
But what happens if that object goes out of scope and gets garbage collected. Right now, the asm.js code has no way of knowing about that, so the memory of the structure will remain allocated, causing a memory leak.
Is there some way to add a finalizer to a JavaScript object from within JavaScript?
Such a finalizer could be used to deallocate the memory in asm.js, thus avoiding the memory leak. So far I couldn't find a documented i.e. portable way to achieve this, but perhaps I've been looking in the wrong places.
Coming back to this question, I found another answer pointing out that there is a specification for weak references and finalization which some browsers implement. The central component for finalization is FinalizationRegistry.
So depending on which browsers you target, this may be possible now. If you need to support browsers without this feature, using explicit release calls, it might be possible to use the finalizers where supported to detect memory leaks (i.e. objects not explicitly released in JavaScript code) and let the developer know so they can fix this.
The simple answer is that there is no support for this.
Since asm.js code needs to manage its own memory, everything that interacts with objects stored on the asm side need to respect the memory manager that asm uses rather than the memory manager that the browser uses. The best that you can do is to explicitly call a method on any object referencing internal asm memory whenever you create or destroy a reference to it.

Which is the fastest way of accessing JavaScript object?

I want to know what is the best way of accessing a JavaScript object, dot operator or []:
data.property or data["property"]?
Both are more or less the same, except in Safari in which case dot notation is significantly faster.
You're much better off concentrating on DOM manipulation, DOM size, and CSS complexity as major sources of performance problems in Javascript applications.
That said, if you are doing a lot of property access in a loop, a local variable will be much faster than either property access or array lookup. Copy an object property into a variable if it is going to be accessed repeatedly. Do not use the "with" statement, incidentally. It can slow down local variable access by introducing another object into the scope chain.
Variables defined in local scope will be accessed far more quickly than those in global, as the Javascript engine first looks through all of the variables locally, then checks all of the variables in global scope. Scopes can nest as well, so the farther up the nesting chain the variable resides the longer it will take to find. That's why it's best to cache something like "document" in a local variable if it is going to be accessed more than once.
Both are the same speed. Also, if you are concerned with the level of speed in accessing a field attached to a reference, I think you might be going down the wrong path to tuning your code.
I would venture to guess that data.property is ever-so-slightly faster, but it may be difficult to measure. Indeed, JSPerf shows no distinction
The best way of accessing object properties has generally nothing to do with speed. Dot operator is used for syntactic sugar (I.E. this.hasElements() is easier to read, write and process in your brain than this["hasElements"]()) whenever possible and the brackets are used when the key name is a variable or has illegal characters.

Lifetime of JavaScript variables

What is the lifetime of a variable in JavaScript, declared with "var".
I am sure, it is definitely not according to expectation.
<script>
function(){
var a;
var fun=function(){
// a is accessed and modified
}
}();
</script>
Here how and when does JavaScript garbage collect the variable a? Since a is a part of the closure of the inner function, it ideally should never get garbage collected, since the inner function fun, may be passed as a reference to an external context. So fun should still be able to access a from the external context.
If my understanding is correct, how does garbage collection happen then, and how does it ensure to have enough memory space, since keeping all variables in memory until the execution of the program might not be tenable ?
The ECMAScript specification does not specify how the garbage collector should work, it only says that if an identifier is reachable (through a direct pointer or a closure), it shouldn't be GCed.
Check out this article about identifier resolution, closures, scope chaining and garbage collection in ECMAScript.
Hope it helps
'a' will not be garbage-collected as long as there are external references to 'fun'. The browser ensures it has enough memory by asking for more memory from the OS.

Categories

Resources