miktam / sizeof

Get size of a JavaScript object

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

About Circular structure in Node

halilcakar opened this issue · comments

Hey @miktam, First of all thanks. Let view the situation of a Circular object in node.

In my code I have a USERS object that holds my users personal data's (obvv :) and i was playing around and found out that if I reference my object as Circular object (USERS[3].user = USERS[3];)
it gives me this value: 11076980 bytes = ~10.56 MB but when i remove my reference(or not create in this matter) it gives me: 1940 bytes = ~0.0018MB which is quite a difference 😄

I saw that u have this:

sizeof/index.js

Lines 20 to 29 in 81557e3

try {
bytes += sizeof(object[key])
} catch (ex) {
if (ex instanceof RangeError) {
// circular reference detected, final result might be incorrect
// let's be nice and not throw an exception
bytes = 0
}
}
}

But it really doesn't detect Circular objects. What do you think about this ?

@halilcakar right, correct way to implement circular dependencies would be to hold a structure (eg Set) of all the objects, and do not count duplicates.
let me think about this a bit more and will get back to you.

That's actually not a problem for my case, but when i saw i just wanted to write about it cause it might me someone else's case. I'm also gonna look into this, let you know if i would find some solution about it :)

I have the same problem. Infinitely considers

Doing the following means sizeof(object[key]) is never called as it only continues if object doesn't have key as a property.

if (!Object.hasOwnProperty.call(object, key)) {
  continue
}

Instead can check if it references itself like if (object[key] === object) or create a WeakSet to not count duplicates as suggested above.