Record is currently implemented with a Map. But because it has a fixed size, and because the keys are always strings, it's possible to use a much simpler and faster implementation.
To lookup a key in the Record, you first look it up in _keys which gives you an index, and then you lookup that index in _values.
To set a key in a Record, you first look it up in _keys, which gives you an index. You then make a copy of the _values array, mutate the index to be the new value, then return a new Record with the new _values array.
There are a few reasons this is fast:
I have implemented this technique in my library, and you can find the benchmarks here:
Getting is always super fast. Setting is fast until you reach around 1,000 keys or so, and it's extremely rare to have Records with 1,000+ keys in them, so that isn't a problem.
Yes! Thanks for writing up the whole draft of this, this has been on my wishlist for a while and I appreciate you documenting up the approach.
I'm also interested in this.
@copy Making a copy of an object is very slow: #174 (comment)
As shown in these benchmarks, making a copy of an array is much faster than making a copy of an object. This isn't surprising, since arrays are much simpler data structures than objects.
@Pauan The copy function in that benchmark is pretty bad, using for-in instead of a function specific to the structure of the Record. Optimally, a Record with three properties x, y, z would create a function like:
It probably doesn't matter too much, but your solution has an indirection on every get/set.
@copy Using eval or new Function lets you create a custom function for each Record, however certain systems (like Google Chrome Extensions) forbids eval.
You are right that there is a (very minor) indirection, but you'll note that even with the indirection, it blows the pants off of the other immutable data structures, and is close to mutable object speed for get.
I re-ran the benchmarks, this time adding in a custom function as you suggested:
As you can see, your idea is slower for set than copying an array. Copying an array is really really fast. Objects are fundamentally more complex than arrays.
In any case, thanks for the idea (and the video), even if it didn't pan out in the end. I'm always willing to learn new techniques to make these data structures faster.
Thank you for reporting this issue and appreciate your patience. We've notified the core team for an update on this issue. We're looking for a response within the next 30 days or the issue may be closed.