如何使一个类的实例同时具有可比性和可垃圾收集性? [英] How do I make a class's instances comparable and garbage collectable at the same time?
问题描述
我正在编写一个 class
并希望实例可以通过 <
, >
, ==代码>.
I'm writing a class
and want the instances to be comparable by <
, >
, ==
.
对于 <
和 >
,valueOf
工作正常.
For <
and >
, valueOf
works fine.
==
是不同的,但是,但我也想拥有它.我可以很容易地实现一个 isEqual
方法,但那是不一样的.
==
is different, however, but I want to have that as well. I could easily implement an isEqual
method, but that's just not the same.
我目前的解决方案是缓存所有创建的对象:
My current solution is a cache for all the created objects:
const cache = {}
class Comparable {
constructor (id) {
if (cache[id]) return cache[id]
cache[id] = this
}
}
这样,比较就起作用了.不幸的是,这也会阻塞垃圾收集器.
That way, the comparison works. Unfortunately, this also blocks the garbage collector.
是否有另一种方法可以使 new Comparable(42) == new Comparable(42)
不妨碍 GC?
Is there another way of enabling new Comparable(42) == new Comparable(42)
, that does not impede GC?
推荐答案
您似乎在寻找 hashconsing,但正如您所经历的,这无法有效实现,因为 JavaScript 没有(尚未) 支持弱(或软)引用.
You seem to be looking for hash consing, but as you experienced this cannot be implemented efficiently since JavaScript does not (yet) support weak (or soft) references.
不,在 JS 中不可能覆盖任何运算符,包括 ==
.==
将始终通过引用比较两个对象,对此您无能为力.最好的办法是创建一个 compare
方法.
No, it is not possible to overwrite any operators, including ==
, in JS. ==
will always compare two objects by reference, there's nothing you can do about it. Your best bet will be creating a compare
method.
这篇关于如何使一个类的实例同时具有可比性和可垃圾收集性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!