There is one important optimization in V8 (and possibly other JavaScript engines) that is called inline caches:
const x = {
foo: 1,
bar: 2
};
If this object never changes, this optimization allows you to get fast access to properties (x.foo). Without optimizations, the runtime would need to do a dictionary lookup each time. But with the optimization, the lookup is closer to compiled languages where the data structure is statically known.
Back to your question: for this important optimization to kick in, it will not matter if you initialized the object as above or like this:
const x = {};
x.foo = 1;
x.bar = 2;
There may be minor performance differences, but you will get the important optimization in both cases. Thus, if you keep using the object, I would not expect significant differences.
However, there are a couple of non-obvious pitfalls, which will prevent the optimization (depends on the JavaScript runtime but should apply to V8).
- properties should be initialized in the same order
- avoid removing fields later with
delete
The reason for 1) is that if you add a property, it will internally create a new hidden class. So, you will get a second hidden class if you would have swapped the initialization order:
const y = {};
y.bar = 2;
y.foo = 1;
Note there is a semantic difference between x and y (e.g. Object.keys(x) -> ['foo', 'bar'] but Object.keys(y) -> ['bar', 'foo']).
But otherwise, it is better for performance to always initialize fields in the same order; especially if you have multiple fields. With fewer permutations, the number of hidden classes is also lower. That helps the inline caches optimization.
Regarding delete: the optimization can handle new fields being added (up to a certain number), but if you delete fields, it will fallback to dictionary lookups. To the best of my knowledge, once it is in that state, the object will never be able to reach fast lookups again. That is why delete may come with a performance hit in certain workloads. In that case, consider keeping the field, but zeroing it out (e.g. setting it to null).