What is the complexity of Typescript Record access knowing the key?

Viewed 385

I read in this question that Javascript's Map has O(1) complexity for retrieval/access. Typescript has Records which have an advantage: being typed. However, I was wondering if Typescript's Records give us the same access performance. Should we be using plain JS maps to optimize data access speed?

1 Answers

I read in this question that Javascript's Map has O(1) complexity for retrieval/access.

That question is specifically about the implementation of Map in the V8 JavaScript engine (in 2015). You can't generalize it to maps in other implementations, and O(1) is not guaranteed by the specification. All that's guaranteed is that access will be sublinear on the number of entries in the Map.

Typescript has Records which have an advantage: being typed. However, I was wondering if Typescript's Records give us the same access performance.

TypeScript's Record type is purely a compile-time abstraction over a JavaScript object. So the question is: Is the access time for properties of a JavaScript object at least as good as the access time of accessing entries in a JavaScript Map?

It depends, but generally yes. In fact, for objects with stable sets of properties, it's likely to be dramatically faster in cases where it matters, because in cases where it matters, modern JavaScript engines compile objects to runtime-generated classes with static slots for properties, so accessing those properties is a constant-time operation (O(1)).

But, if the contents of your objects vary over time (the set of properties is not relatively static), the optimizations done for objects aren't appropriate and you may be better off with a Map.

Note that there are other reasons than performance to choose an object over a Map, or a Map over an object. For instance, a Map's keys can be anything, but an object's keys can only be strings or Symbols. Accessing a value in a Map requires a function call; not so object properties. Etc.

More on MDN.

Related