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
ephemient
04/28/2021, 12:58 AM
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
David Smith
04/28/2021, 1:00 AM
so in the code I have written, does this mean that calling