Garbage collection of deleted array element - javascript

If I have a large array I'm using all the time and continuously through-out the lifetime of the app, such as a user list. And yes I enjoy using arrays rather than objects for many reasons and can't use splice() because I have index references.
The usual quote for garbage collection:
Since Javascript is garbage collected, you don't need to delete
objects themselves - they will be removed when there is no way to
refer to them anymore.
Does this mean that when I delete an element in an array, since the array can be referred to at any time - the Garbage collector wont free up the deleted element? or does it mean because the object can't be referred to, it will free up memory? - And even if it is, wont my array get filled up with 'undefined' entries which presumably use up at least 1 or 2 bytes of memory? - does anyone know how much memory is used per undefined entry?
Example:
var userList = [];
var userNumber = 0;
userList[userNumber++] = {name:'john',score:200,friends:['abby','micky']};
userList[userNumber++] = {name:'jack',score:200,friends:['betty','billy']};
userList[userNumber++] = {name:'jimm',score:200,friends:['catty','ken']};
delete userList[1];
// will {name:'jack',score:200,friends[ n ]} size of memory be freed
// or a little less to internally reference 'undefined'?

When you delete an array property, its value becomes unreachable*, hence freeable by the garbage collector as soon as you delete them.
a = [0, 1, 2]
alert(1 in a); // true
delete a[1];
alert(1 in a); // false
* - assuming the array element is not otherwise reachable from a property of a reachable object or live local variable.
... - the Garbage collector wont free up the deleted element? or does it mean because the object can't be referred to, it will free up memory?
The garbage collector is never obliged to free any memory, but can reuse any memory previously used by the value of a deleted array property that is not otherwise referenced by any property or live local variable.

Related

WeakSet: garbage collection doesn't work? [duplicate]

The WeakSet is supposed to store elements by weak reference. That is, if an object is not referenced by anything else, it should be cleaned from the WeakSet.
I have written the following test:
var weakset = new WeakSet(),
numbers = [1, 2, 3];
weakset.add(numbers);
weakset.add({name: "Charlie"});
console.log(weakset);
numbers = undefined;
console.log(weakset);
Even though my [1, 2, 3] array is not referenced by anything, it's not being removed from the WeakSet. The console prints:
WeakSet {[1, 2, 3], Object {name: "Charlie"}}
WeakSet {[1, 2, 3], Object {name: "Charlie"}}
Why is that?
Plus, I have one more question. What is the point of adding objects to WeakSets directly, like this:
weakset.add({name: "Charlie"});
Are those Traceur's glitches or am I missing something?
And finally, what is the practical use of WeakSet if we cannot even iterate through it nor get the current size?
it's not being removed from the WeakSet. Why is that?
Most likely because the garbage collector has not yet run. However, you say you are using Traceur, so it just might be that they're not properly supported. I wonder how the console can show the contents of a WeakSet anyway.
What is the point of adding objects to WeakSets directly?
There is absolutely no point of adding object literals to WeakSets.
What is the practical use of WeakSet if we cannot even iterate through it nor get the current size?
All you can get is one bit of information: Is the object (or generically, value) contained in the set?
This can be useful in situations where you want to "tag" objects without actually mutating them (setting a property on them). Lots of algorithms contain some sort of "if x was already seen" condition (a JSON.stringify cycle detection might be a good example), and when you work with user-provided values the use of a Set/WeakSet would be advisable. The advantage of a WeakSet here is that its contents can be garbage-collected while your algorithm is still running, so it helps to reduce memory consumption (or even prevents leaks) when you are dealing with lots of data that is lazily (possibly even asynchronously) produced.
This is a really hard question. To be completely honest I had no idea in the context of JavaScript so I asked in esdiscuss and got a convincing answer from Domenic.
WeakSets are useful for security and validation reasons. If you want to be able to isolate a piece of JavaScript. They allow you to tag an object to indicate it belongs to a special set of object.
Let's say I have a class ApiRequest:
class ApiRequest {
constructor() {
// bring object to a consistent state, use platform code you have no direct access to
}
makeRequest() {
// do work
}
}
Now, I'm writing a JavaScript platform - my platform allows you to run JavaScript to make calls - to make those calls you need a ApiRequest - I only want you to make ApiRequests with the objects I give you so you can't bypass any constraints I have in place.
However, at the moment nothing is stopping you from doing:
ApiRequest.prototype.makeRequest.call(null, args); // make request as function
Object.create(ApiRequest.prototype).makeRequest(); // no initialization
function Foo(){}; Foo.prototype = ApiRequest.prototype; new Foo().makeRequest(); // no super
And so on, note that you can't keep a normal list or array of ApiRequest objects since that would prevent them from being garbage collected. Other than a closure, anything can be achieved with public methods like Object.getOwnPropertyNames or Object.getOwnSymbols. So you one up me and do:
const requests = new WeakSet();
class ApiRequest {
constructor() {
requests.add(this);
}
makeRequest() {
if(!request.has(this)) throw new Error("Invalid access");
// do work
}
}
Now, no matter what I do - I must hold a valid ApiRequest object to call the makeRequest method on it. This is impossible without a WeakMap/WeakSet.
So in short - WeakMaps are useful for writing platforms in JavaScript. Normally this sort of validation is done on the C++ side but adding these features will enable moving and making things in JavaScript.
(Of course, everything a WeakSet does a WeakMap that maps values to true can also do, but that's true for any map/set construct)
(Like Bergi's answer suggests, there is never a reason to add an object literal directly to a WeakMap or a WeakSet)
By definition, WeakSet has only three key functionalities
Weakly link an object into the set
Remove a link to an object from the set
Check if an object has already been linked to the set
Sounds more pretty familiar?
In some application, developers may need to implement a quick way to iterate through a series of data which is polluted by lots and lots of redundancy but you want to pick only ones which have not been processed before (unique). WeakSet could help you. See an example below:
var processedBag = new WeakSet();
var nextObject = getNext();
while (nextObject !== null){
// Check if already processed this similar object?
if (!processedBag.has(nextObject)){
// If not, process it and memorize
process(nextObject);
processedBag.add(nextObject);
}
nextObject = getNext();
}
One of the best data structure for application above is Bloom filter which is very good for a massive data size. However, you can apply the use of WeakSet for this purpose as well.
A "weak" set or map is useful when you need to keep an arbitrary collection of things but you don't want their presence in the collection from preventing those things from being garbage-collected if memory gets tight. (If garbage collection does occur, the "reaped" objects will silently disappear from the collection, so you can actually tell if they're gone.)
They are excellent, for example, for use as a look-aside cache: "have I already retrieved this record, recently?" Each time you retrieve something, put it into the map, knowing that the JavaScript garbage collector will be the one responsible for "trimming the list" for you, and that it will automatically do so in response to prevailing memory conditions (which you can't reasonably anticipate).
The only drawback is that these types are not "enumerable." You can't iterate over a list of entries – probably because this would likely "touch" those entries and so defeat the purpose. But, that's a small price to pay (and you could, if need be, "code around it").
WeakSet is a simplification of WeakMap for where your value is always going to be boolean true. It allows you to tag JavaScript objects so to only do something with them once or to maintain their state in respect to a certain process. In theory as it doesn't need to hold a value it should use a little less memory and perform slightly faster than WeakMap.
var [touch, untouch] = (() => {
var seen = new WeakSet();
return [
value => seen.has(value)) || (seen.add(value), !1),
value => !seen.has(value) || (seen.delete(value), !1)
];
})();
function convert(object) {
if(touch(object)) return;
extend(object, yunoprototype); // Made up.
};
function unconvert(object) {
if(untouch(object)) return;
del_props(object, Object.keys(yunoprototype)); // Never do this IRL.
};
Your console was probably incorrectly showing the contents due to the fact that the garbage collection did not take place yet. Therefore since the object wasn't garbage collected it would show the object still in weakset.
If you really want to see if a weakset still has a reference to a certain object then use the WeakSet.prototype.has() method. This method, as the name implies returns a boolean indicating wether the object still exists in the weakset.
Example:
var weakset = new WeakSet(),
numbers = [1, 2, 3];
weakset.add(numbers);
weakset.add({name: "Charlie"});
console.log(weakset.has(numbers));
numbers = undefined;
console.log(weakset.has(numbers));
Let me answer the first part, and try to avoid confusing you further.
The garbage collection of dereferenced objects is not observable! It would be a paradox, because you need an object reference to check if it exists in a map. But don't trust me on this, trust Kyle Simpson:
https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/es6%20%26%20beyond/ch5.md#weakmaps
The problem with a lot of explanations I see here, is that they re-reference a variable to another object, or assign it a primitive value, and then check if the WeakMap contains that object or value as a key. Of course it doesn't! It never had that object/value as a key!
So the final piece to this puzzle: why does inspecting the WeakMap in a console still show all those objects there, even after you've removed all of your references to those objects? Because the console itself keeps persistent references to those Objects, for the purpose of being able to list all the keys in the WeakMap, because that is something that the WeakMap itself cannot do.
While I'm searching about use cases of Weakset I found these points:
"The WeakSet is weak, meaning references to objects in a WeakSet are held weakly.
If no other references to an object stored in the WeakSet exist, those objects can be garbage collected."
##################################
They are black boxes: we only get any data out of a WeakSet if we have both the WeakSet and a value.
##################################
Use Cases:
1 - to avoid bugs
2 - it can be very useful in general to avoid any object to be visited/setup twice
Refrence: https://esdiscuss.org/topic/actual-weakset-use-cases
3 - The contents of a WeakSet can be garbage collected.
4 - Possibility of lowering memory utilization.
Refrence: https://www.geeksforgeeks.org/what-is-the-use-of-a-weakset-object-in-javascript/
##################################
Example on Weakset: https://exploringjs.com/impatient-js/ch_weaksets.html
I Advice you to learn more about weak concept in JS: https://blog.logrocket.com/weakmap-weakset-understanding-javascript-weak-references/

using shift with an empty input js

I have a basic question about using the .shift method. Below is my working code to convert a number to the sum of all digits. After converting to string and splitting to array, if the first value is the '-' sign I use .shift to remove this element, then make the next value negative. My question is, where does the '-' go? What happens to this value that I have not assigned to any variable?
Moving forward, should I be concerned about using this method if it will potentially leave values sort of 'floating' around in my code?
function sumDigits(num) {
var numArr = num.toString().split('');
if (numArr[0] === '-') {
numArr.shift();
numArr[0] *= -1;
}
var total = numArr.map(Number).reduce(function(a, b) {
return a + b;
});
return total;}
Thanks!
Since arrays in Javascript are mutable, each element in an array is a reference to a place in memory. When you create a new array or add an element to an array, Javascript implicitly allocates memory and then creates new references from the array to point to the newly allocated objects in memory.
In your situation, when you shift(), you're removing the reference to the memory that contains that element, and not the element itself.
So how does Javascript actually delete these items from memory? Garbage collection. One simple mechanism of garbage collection checks all of the objects in memory and counts the number of references to it. If the number of references is 0, then it indicates to the garbage collector that the object can be deleted from memory.
So when after you delete the reference to the first element in the array with shift(), the garbage collector later comes in and sees that the object that the first element in the array used to point to now has nothing that references it. Thus it is safe to garbage collect, and is therefore deallocated from memory.
All in all, you do not need to worry about memory leaks from using shift() thanks to Javascript's garbage collection mechanism.
Here is an interesting link about Javascript memory management, if you're curious to learn more.

Do identical chrome object ids imply the same object in the heap profiler?

I am working through a memory issue with one of our webapps. I am using Chrome's heap profiler. I want to make sure I understand something very explicitely, as I'm making assumptions on this information.
The # symbol in the heap profile screenshot above. I want to make sure I understand crystal clear: equal object ids implies the same object
a.objectId == b.objectId implies a same as b
a.objectId == b.objectId implies NOT a same as b
Therefore if I have two objects that I expected to actually be the same thing, yet their object id differs, this implies an unexpected copy occurred? This implies I can go and figure out in my code where I might be creating unnecessary duplicates?
The documentation appears to say this, but they don't quite say it explicitly, going on to say why they have an object id, not what it represents.
This is an object ID. Displaying an object's address makes no sense, as objects are moved during garbage collections. Those object IDs are real IDs — that means, they persist among multiple snapshots taken and are unique. This allows precise comparison between heap states. Maintaining those IDs adds an overhead to GC cycles, but it is only initiated after the first heap snapshot was taken — no overhead if heap profiles aren't used.
I get that. But I need to fit this back into my C programmer head. I realize, even with native heaps, pointer values can change over time. Can I effectively treat object ids as pointer addresses unique over time?
So I ran some test code in Chrome and the answer appears to be yes, the same object id implies identical objects. If object id differs, this implies a copy or different object altogether.
I profiled the following snippet of code which can be found in this github repo:
(function heapTest(doc) {
'use strict';
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
var b = {'grandchild-key-2': 5};
var a = {'child-key-1': b};
doc.child1 = a;
doc.child1_again = a;
doc.child1_copy = clone(a);
})(document);
The heap profiler confirms the two references share object ids, the copy receives a new object id.
In short, this behaves like I expect. Multiple references to the same object receive the same object id. Copies refer to a different object and receive a different object id.

How does the browser's javascript garbage collection work?

Do I have to destroy instances myself? ...if I don't assign them a variable...will they automatically go away?
new ImageUploadView();
vs
var Iu = ImageUploadView();
If there is no reference to an object in javascript, the garbage collector will clean it up.
The way the garbage collector works is it looks for javascript objects for which nobody has a reference to. If nobody has a reference to it, then it can't be used again, so it can be deleted and the memory it occupied reclaimed. On the other hand, if any javascript entity still has a reference to the object, then it is still "in use" and cannot be deleted.
In your first code example:
new ImageUploadView();
unless the constructor of the object stores away the this pointer into some other variable or object or creates some closure that causes references to the object to be held, then there will be no reference to this new object and it will be cleaned up by the garbage collector.
If you second code example:
var Iu = ImageUploadView();
as long as the Iu variable exists and stays in scope it will contain whatever the ImageUploadView() function returns. Note, the second example, is just executing a function and storing it's value. It is not necessarily creating anything. If ImageUploadView() just returns true, then that's all the Iu variable will contain.
The first method is fine. Assuming that the instance of ImageUploadView is appropriately cleaning up after itself, it will be collected by the garbage collector.
With large objects, it's not necessarily a good practice to assume that the browsers built in garbage collector will clean up once it's out of scope. You're better off to clear it ourself using "delete". For example:
delete MyImageUploadView;
Edit: it may be preferable to set the object to null if it isnt being referenced as a property.

Deallocating memory used by Javascript objects

Should I free the allocated memory by myself, or is there a kind of garbage collector?
Is it okay to use the following code in JavaScript?
function fillArray()
{
var c = new Array;
c.push(3);
c.push(2);
return c;
}
var arr = fillArray();
var d = arr.pop()
thanks
Quoted from the Apple JavaScript Coding Guidelines:
Use delete statements. Whenever you
create an object using a new
statement, pair it with a delete
statement. This ensures that all of
the memory associated with the object,
including its property name, is
available for garbage collection. The
delete statement is discussed more in
“Freeing Objects.”
This would suggest that you use a delete command to then allow the garbage collector to free the memory allocated for your Array when you're finished using it. The point that the delete statement only removes a reference is worth noting in that it differs from the behaviour in C/C++, where there is no garbage collection and delete immediately frees up the memory.
Memory management in JavaScript is automatic and there is a garbage collector (GC).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
You cannot explicitly delete the variables d and arr, but you can remove references to their value by setting the variables to something else, such as null, to allow the GC to remove them from memory.
arr = null;
d = null;
Note that the delete keyword only deletes object properties.
The variables arr and d will exist as global variables and will exist until they are collected by the Garbage Collector.
The variables will be set as properties on the global object i.e. window in a browser environment but since they are declared with var, they will not be deletable from the global object.
In your particular case, the best course of action might be to assign null to the variables after you are finished with them. You may also want to consider containing their scope to a function and do what you need to do with them inside that function.

Categories

Resources