javascript – What structure should be used to store data that is quickly added and removed?

Question:

There are a large number of objects (~10000+), in which about 50 previously known new properties (with different values) can be added in random order. When a property has already been used and is no longer needed, it is deleted via delete

* In particular, this happened in the game: The system of combat effects of characters, when exchanging blows every couple of seconds, all bots regularly turn on / off different effects.

If you search Google for something like “js engine optimization”, you can find articles ( example-1 , example-2 ) stating that the “hidden class” mechanism is used when creating objects:

function Point(x, y) {
  this.x = x;
  this.y = y;
}

var p1 = new Point(1, 2);
p1.a = 5;
p1.b = 6;

var p2 = new Point(3, 4);
p2.b = 7;
p2.a = 8;

JS creates one hidden class for p1 and another one for p2 because properties a and b are added in a different order. Accordingly, it is recommended to initially add all properties in the same order.

Hence the questions:

  1. Does this mechanism have any restrictions on the maximum number of created classes? Obviously, for 50 properties, it is physically impossible to create 50! classes. (Or am I misunderstanding how it works?)
  2. Create objects with the same but empty properties, and instead of delete, give them null / undefined values ​​- Good or bad? Initially, it seemed that using delete, I freed memory from unnecessary properties. But in reality it turns out, it only clogs it – by creating new hidden classes, when adding new properties?

Answer:

  1. "When a property is created dynamically, or a property is deleted or changed, another hidden class is created.". That is, every time a property is created, a class is dynamically created, that is, how many properties only and classes (in general, a class is created not only when a property is created, but also when changing and deleting, but it will be easier this way) there are practically no limits on this (certainly no less than properties) .
  2. Assigning null / undefined and delete are the same thing. In general, for small arrays / objects, delete is suitable because it will be possible to use the filter method to clean it from everything superfluous, but in the case of a large array / object (~ 10000+), this method is not suitable. And yes, it only clogs memory more instead of clearing it.
Scroll to Top