Let's say you want to compare two javascript objects or arrays for reference equality.
The most obvious solution would be
if (a === b) { /*...*/ };
The problem with this is that a
and b
would have to hold the references to actual objects. This can be a problem in same cases. For example, trying to hold actual references in a memoization function would create a memory leak.
One approach is to use JSON.stringify(a)
to obtain string representations of objects and compare that. But that can be prohibitively expensive in some use cases. Not to mention that actual reference equality isn't taken into consideration.
That got me wondering. Is there a way to stringify an actual reference instead of the object contents? Obviously, you can't manipulate pointers in javascript, but what if you could get just a pointer representation of some kind. A hash sum? Raw memory location? Guid or integer representation?
I know there are some kinds of object id-s when analyzing memory dump in chrome dev tools. Maybe these things can be accessed during runtime? Using some kind of special switch in node.js?
Can anyone think of a way to get this done in javascript?