Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objects as keys in maps: Memory duplication?

I would like to map from objects that already exist elsewhere in the code, to, say, numbers.

var map = new Map();
var keyObj = {a: "b"};

map.set(keyObj, 3);

Does keyObj now exist twice in memory? Or is only a address to the original keyObj stored in the map?

like image 456
reign Avatar asked May 24 '26 15:05

reign


1 Answers

Objects (anything that isn't a primitive) are for most intents and purposes shared pointers, whenever you assign them another reference to them is made, when all references are gone it gets deleted (or rather garbage collected at JS's leasure).

let a = {v: 3}; // a stores a reference to the object
let b = a; // b stores a reference to the same object
assert(a === b); // these are both references to the same object
a = undefined;
assert(b.v === 3); // the object doesn't get deleted if one of the references disappears

References to different objects aren't the same

let a = {v: 3}; // object 1
let b = {v: 3}; // object 2
assert(a !== b); // not a reference to the same object

Think of it as any variable that holds an object is actually holding an id of an object and that's what is used for comparison

This applies to map keys and sets aswell

let myset = new Set();
let a = {v: 3}; // object 1
let b = {v: 3}; // object 2
assert(set.size === 0); // empty set
myset.add(a); // add a to the set
assert(set.size === 1);
myset.add(a); // a is already in the set
assert(set.size === 1);
myset.add(b); // b is not in the set
assert(set.size === 2);
// note that the item in the set is just as much of a reference as a and b still are
// you can still edit them
a.v = 4;
console.log(myset);
> {{v: 4}, {v: 3}};
a = {} // a now points to a different object, it doesnt override the value of what it used to b

I know this is a bit waffley but I hope it clears any confusion

like image 124
SollyBunny Avatar answered May 27 '26 08:05

SollyBunny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!