understanding cross-reference in reference counting method of garbage collection - javascript

While reading a book I came to know that implementations of JavaScript tend to use one of the two garbage collection methods. Either it is mark-and-sweep, or reference counting. I understand the concept of reference counting. It is counted that how many references of a value exists. When a variable is assigned a value, reference counting for that variable increases by 1 and when variables are overridden by some other value, reference counting of 'THIS' value decreases by 1. The process continues and when number of references reaches to 0, the value is considered safe for deletion.
Then there was a section explaining the cross-reference problem with reference-counting method in garbage collection. It says, whenever a property of object A is assigned the reference to object B and vice-versa, then the cross-reference problem arrives because the counting never reaches to zero. The example given in the book was something like this
var A = new Object();
var B = new Object();
A.prop = B;
B.prop = A;
I completely missed this. I mean, how the above code results in a cross-reference problem? Why the counting never reaches zero.
Note I wrote everything I understood about reference counting. If I am wrong somewhere, pleas tell. Thanks.

This is an example:
class Person{
string name;
Person lover;
}
A = new Person("A");
B = new Person("B");
A.lover = B;
B.lover = A;
A = NULL;
B = NULL;
So, the counting never reaches zero.

Related

Assigning one array to another javascript

So array in javascript are assigned by references so for example
let a = [1,2,3];
let b = a;
a = [];
console.log(b);
Shouldn't it print empty array as a is assigned to empty array and b and a are point to same.
I know that such behavior might seem weird. However, as other writers already mentioned, what happens is that by writing ‘a = []’ you actually assigned ‘a’ a new reference (i.e. you are not manipulating the ‘old’ array any more), and ‘b’ will hold an old reference to a memory location where ‘old’ array was initially assigned and break a relationship with ‘a’. Hence, there will now exist 2 references instead of an initial 1.

Setting a variable equal to another variable [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 2 years ago.
I have a few questions about setting a variable equal to another variable in JavaScript.
Let's say we create an object, a and set b = a.
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
I understand that if we change one of a's properties b will also be changed because when we set b = a we don't clone a's data, but rather create a reference to a's data. For example if we set a.fname = "Sarah", the new value of b.fname will be "Sarah".
If we try to "clear" a though by setting a = {}, object b will remain unchanged. I don't understand why manipulating an object in this way produces a different result than in the 1st example.
Also I have a question about the following scenario.
var x = 10;
var z = x;
If we then set x = 20, the value of z remains unchanged. Based on the behavior described in my 1st question, one would think that the new value of z would reflect the new value of x. Could someone please explain what I am missing here?
Thank You!
The really short answer to both your questions is that when you make one variable equal to another, a COPY of what's in the first variable is made and stored in the second variable - there is no linkage between the two variables.
But, read on for more details and why it can seem like there is a link in some cases...
JavaScript, like many languages, divides data into two broad categories: value types and reference types. JavaScript value types are its primitives:
string
number
boolean
null
undefined
symbol
When you assign any of these types to a variable, the actual data is stored in that variable and if you set one variable equal to another, a copy (not a linkage) of the primitive is made and stored in the new variable:
var a = 10; // Store the actual number 10 in the a variable
var b = a; // Store a COPY of the actual number stored in a (10) in the b variable
a = 50; // Change the actual data stored in a to 50 (no change to b here)
console.log("a is: " + a); // 50
console.log("b is: " + b); // 10
When you work with reference types, something a little different happens. Assigning a variable to a reference type means that the variable only holds a reference to the memory location where the object is actually stored, not the actual object itself. So, when you do this:
var a = {foo:"bar"};
a does not actually store the object itself, it only stores the memory location for where the object can be found (i.e. 0x3C41A).
But, as far as setting another variable equal to the first goes, it still works as it did with primitives - - a copy of what's in the first variable is made and given to the second variable.
Here's an example:
// An object is instantiated in memory and a is given the address of it (for example 0x3C41A)
var a = {};
// The contents of a (the memory location of an object) is COPIED into b.
// Now, both a and b hold the same memory location of the object (0x3C41A)
var b = a;
// Regardless of whether a or b is used, the same underlying object
// will be affected:
a.foo = "test";
console.log(b.foo); // "test"
// If one of the variables takes on a new value, it won't change
// what the other variable holds:
a = "something else";
console.log("a is: ", a); // The new string primitive stored in memory
console.log("b is: ", b); // The object stored in memory location (0x3C41A)
So, in your first tests, you've simply got two ways of accessing one object and then you change what a is holding (the memory location of the object) to a different object and therefore now you only have one way left to access the original object, through b.
If we try to "clear" a through by setting a = {}, object b will remain
unchanged. I don't understand why manipulating an object in this way
produces a different result than in the 1st example.
Because now we know that a = {} isn't clearing the object. It's just pointing a at something else.
In your first case:
var a = {
fname: "Jon",
lname: "Smith",
age: 50
}
var b = a;
a = {}
b remains unchanged because this is the sequence of events happening in the background:
You create an object at memory address 0x1234 with the data
fname: "Jon",
lname: "Smith",
age: 50
A pointer to that memory block is stored ina.
Then that pointer is copied to b
At this point there are two references to the same bit of memory. Altering anything in that memory block will affect both the references to it.
a = {} doesn't clear out memory block 0x1234, but creates a new object on another memory location (0x1235) and stores a pointer to that block in a. The memory at 0x1234 remains unchanged because b is still pointing to it.
There is a difference in this sort of memory management between simple variables and objects/pointers. Strings and numbers are of the simple variety and are 'passed by value' as opposed to being 'passed by reference' for objects.
Let me try to explain:
1) In your example a and b are references to one and the same object, while a.fname (or b.fname) is an attribute of that object. So when manipulating the attribute it will be changed in the object, while the references won't be affected, they still point to the same object, the object itself has been changed. a = {} on the other hand will just replace the reference to the object without affecting the object itself or b's reference to It. It's no clearance btw you only just created a new reference to a new empty object.
2) These are not objects, so there is no reference you are directly manipulating the values. That' s because there's a difference between objects and primitives which might get confusing especially in the beginning if you're not used to working with strict types.

Why number are immutable in Javascript?

I have read the question and answer here:
javascript numbers- immutable
But it's not enough clear for me why the number (primitive type) are immutable? Just because they create a new reference but not overwrite the value?
If on each assignemt is created a new reference
var x = 5;
x = 1;
Would we have 100 times a new reference in the following loop?
while (x < 101)
{
x++;
}
Is that efficient? I think I am not seeing correctly.
I'm honestly not quite sure what kind of answer you expect since I don't quite understand what you are confused about. But here we go:
Would we have 100 times a new reference in the following loop?
Variables are just containers for values. At a low level a variable is basically just a label for a memory address or a register. E.g. variable x might point to register R1.
x++ would simply increment the number that is stored in that register by 1. Lets assume our register looked like this:
R1: 5
After incrementing it, which can be a single operation, such as ADD R1 1, we would get
R1: 6
I.e. we simple overwrote the previous value with a new one. And we do that multiple times.
Is that efficient? I think I am not seeing correctly.
Incrementing a number by one is as simple of an operation as it can get.
Sure, you could implement mutable numbers on a higher level, but it certainly wouldn't make things more efficient or simpler.
Mutability doesn't make much sense for "single value" values, because mutating such a value basically means replacing it with a different value "in place".
Mutability makes more sense for values that are composed of other values such as lists and dictionaries, where one part changes and the other stays the same.
Additionally, mutability only seems relevant when a language has reference type data types. With that I mean that multiple variables can hold a reference to the very same value of a data type. Objects are reference-type in JavaScript, which allows you to do this:
var a = {foo: 42};
var b = a;
b.foo = 21;
console.log(a);
If data types are not of a reference-type, called value-type, (which primitive values are in JavaScript), then mutability doesn't matter because it would be indistinguishable from immutability. Consider the following hypothetical scenario with a mutable, value-type number:
var a = MutableNumber(42);
var b = a; // creates a copy of MutableNumber(42) because it's a value type
a.add(1);
console.log(a, b); // would log 43, 42
In this scenario it is not possible for two variables to refer to the same mutable number value, a.add(1) is indistinguishable from assigning a new value to a (i.e. a = a + 1).
I could understand your question , the thing is , inside the while loop , everytime the x will point to the new value , whereas the old value will be made ready for garbage collection , so the memory is mantained still.
Read this for better understanding :
https://developer.mozilla.org/en-US/docs/Glossary/Mutable
So about the mutablity , your understanding is correct , the variable references the new value , the old value isn't changed , hence primitive values are immutable.
Refer: https://developer.mozilla.org/en-US/docs/Glossary/Primitive
Mutation is a change of state while numbers (the primitive type) are pure state objects. Any mutation to such a "object" state is actually a new number. Number itself is like an identifier of a mutation of bits in a cell of computer memory.
Therefore numbers are not mutable. Same as colors or characters.
It is also worth claryfining that a new number will ocupy the same memory cell as the old one for any given variable. Actually replacing the old one. Therefore there is no performance hit of any kind.
i dont understand entirely this,
var a=12;
a=45;
we can infer from ;
1.firstly interpreter allocate a chunk of memory and locate 12 to this area.
actually (a) is label of this memory area.
2.than, interpreter allocate a new memory cell and locate 45 to this area.
lastly (a) is associated with this new memory cell. The memory cell that contain 12 is destroyed by garbage collector.
Primitive values vs. references:
In JavaScript values of type boolean, undefined, null, number, symbol, string are primitive. When you assign them to a variable or pass them as an argument to a function, they always get copied.
In contrast objects have two parts to them: Object (it's data) is stored in one chunk of memory and what you assign to a variable is a reference pointing to that object. Object itself is not copied on assignment.
Because numbers are always copied when you assign them to a variable it is impossible to change a number and see that change through some other variable without actually assigning a new value to that variable.
In contrast when you change a field on an object, all variables pointing to that object will see that change.
Let's see some examples:
var a = 1;
var b = a; //This creates a new copy of value 1
console.log(a, b); // 1 1
a = 2;
console.log(a, b); // 2 1
var obj_a = {attr: 1};
var obj_b = obj_a; //This makes a new reference to the same object.
console.log(obj_a, obj_b); // {'attr': 1} {'attr': 1}
obj_b.attr = 2;
console.log(obj_a, obj_b); // {'attr': 2} {'attr': 2}
Immutable objects: immutable.js
Libraries like immutable.js provide types that combine properties of primitive types and objects: Types from immutable.js behave as ordinary objects as long as you don't change them. When you change a property of an immutable object, a new object is created and the change is only visible through that new object. The benefit is that you save space in memory and you can quickly check equality of objects by just comparing their references. You get a set of types that behave like integers but you can store more complex structures in them.

javascript: modifying second variable modifies first

I was trying to understand some javascript and found some quite unexpected behavior. Not knowing much about this language I wanted to find out what this behavior is called so that I can read about it formally.
Here's an example of the behavior:
var test={'x':2};
var test2=test;
test2.sourceLinks = [];
console.log('test',test);
console.log('test2',test2);
To my amazement, I found that modifying the 2nd variable somehow modifies the first as well. The variable "test" will also have an attribute .sourceLinks = []. Do I understand what's happening correctly, and if so, what's the formal term for this behavior?
I found that the answer to this is covered in How do I correctly clone a JavaScript object? after I posted it, although that covered more than I was asking about.
Behavior is called creating a reference. When variable assigned is an object actually it is not copied, rather the result of assignment is a new reference (pointer) to the object.
This doesn't happen with primitive types:
number,
string,
boolean,
null,
undefined.
But happens with all object types:
object,
Array,
function.
This difference is significant in javascript. When some value should be passed to another scope and it might be modified there it should be passed be reference.
function main(){
var x = 1;
modify(x);
console.log(x);//x remains 1
}
function modify(arg){
arg = 10;
}
Whereas when it is passed as a field of an object, it can be modified via reference to an object:
function main(){
var o = {x : 1};
modifyObj(o);
console.log(o);//o.x now equals 10
}
function modifyObj(arg){
arg.x = 10;
}
It's holding the reference.
When you assign object/array/function to another object/array/function it'll assign reference instead of value.
To overcome this you have to clone it
When declaring a variable in Javascript you are creating an object in memory and the variable in the scope is a pointer to that memory object.
In your example both variables (test and test2) are pointing to the same object. Hence, when you modify the the either variable pointer, it is modifying the same object in memory.

Setting one object equal to another object with the assignment operator in Javascript

I'm coming to javascript from C background. In javascript, when I use the assignment operator to assign one object to another, does it copy the values from one to the another, or do they both now point to the same data?. Or does the assignment operator do anything in this case?
function point_type()
{
this.x = 0;
this.y = 0;
}
var pnt1 = new point_type();
var pnt2 = new point_type();
pnt1.x = 4;
pnt1.y = 5;
pnt2 = pnt1;
pnt1.x = 8;
pnt2.y = 9;
In the example above, does pnt2.x now equal 8, or does it still equal 4, or does it still equal 0?
Yes, I realize I can test this myself, and I will be doing that while I wait for the community to come up with an answer. However, I'm hoping the answer to my question will go one step past just answering this one example and might shine some light on how javascript objects work and some best practices.
Follow up question:
The answer seems to be that the reference is copied. pnt2 and pnt1 now point to the same data. Is it possible to set up my object so that the values are copied? How is this usually accomplished in javascript? Clearly I don't want to set each attribute individually every time I need to copy this object.
Whenever I need to copy one object to another in JS, I just cast it to a primitive:
var newObject = JSON.stringify(oldObject);
Then when I need to use it:
var evenNewerObj = JSON.parse(newObject);
Hope this helps someone.
In JavaScript, primitive types are copied by value and reference types are copied by reference. More info here: http://docstore.mik.ua/orelly/web/jscript/ch09_03.html
It equals 8.
pnt2 = pnt1
That statement is pointing the pnt2 object to the pnt1 object so any modification you do to pnt1 will show up in pnt2.
Given the object you showed in your example, it is setting a reference to the object. If it were a primitive type (number, date) then it would copy the object.

Categories

Resources