I’m playing around with a vdom and for this I need...
# announcements
d
I’m playing around with a vdom and for this I need fast access to a hash of each node, since I’m using data classes I have access to
hashCode()
already but I want to avoid having to call it as a function because during a diff of a deeply nested structure this could happen many many times, i.e. I want to memoize the call. Can I simply add a property that is initialized to
this.hashCode()
? I’ve implemented the following which seems to work (although I haven’t tested it properly yet)
Copy code
sealed class Node {
    data class TextNode(val value: String) : Node() {
        override val hash = this.hashCode()
    }
    data class TagNode(val name: String, val attributes: List<Attribute>, val children: List<Node>) : Node() {
        override val hash = this.hashCode()
    }
    abstract val hash: Int
}
e
1. property getters and setters (unless private or annotated) are method calls 2. unless you have actual benchmark numbers, don't worry about it. JIT might end up inlining the accessors anyway 3. for deep hierarchies, it may make sense to cache hashCode() because data class's default implementation will end up hashing every property every time it is called. but the problem is not method call overhead 🙂
d
so in the code I have written, does this mean that calling
x.hash
is actually calling
x.hashCode()
? I.e.
x.hashCode()
is evaluated every time I call
x.hash
?
I had assumed the
val hash = this.hashCode()
would set the value of
hash
by calling
hashCode()
e
no,
x.hash
is actually calling
x.getHash()
, it is still caching
hashCode()
1
if you had written
Copy code
override val hash: Int
    get() = hashCode()
then
x.hash
(a.k.a.
x.getHash()
) would be calling
hashCode()
every time
1