[英]How to avoid memory fragment when allocate large number of objects in JavaScript or TypeScript?
Here is the examble code in TypeScript:这是 TypeScript 中的示例代码:
class Cell {
public index: number = 0;
public m: number = -1;
public n: number = -1;
public g: number = 0;
public h: number = 0;
public prev: Cell = null;
}
let cellArray: Array<Cell> = new Array<Cell>();
for (let i = 0; i < 99999; i++) {
cellArray.push(new Cell());
}
The 999999 Cell objects in stack will cause the problem of memory fragment.堆栈中的 999999 个 Cell 对象会导致 memory 片段的问题。 In C++, I could do like this to allocate one large continuous memory:在 C++ 中,我可以这样做来分配一个大的连续 memory:
new Cell[999999];
Is there any solution to this problem in JavaScript or TypeScript? JavaScript 或 TypeScript 中是否有解决此问题的方法?
You can't control memory allocation explicitly in JS/TS.您无法在 JS/TS 中显式控制 memory 分配。 But, to ensure all object will be in the consecutive order implicitly, you can use ArrayBuffer and one of so called TypedArray .但是,为了确保所有 object 将隐含地处于连续顺序中,您可以使用ArrayBuffer和所谓的TypedArray 之一。 ArrayBuffer allocates single chunk of data in the heap, which you can access via one of the TypedArrays. ArrayBuffer 在堆中分配单个数据块,您可以通过其中一个 TypedArrays 访问它。 Since class Cell have exactly the same number of properties of the same type in each instance, you can save those properties in the buffer, like this:由于 class Cell 在每个实例中具有完全相同数量的相同类型的属性,因此您可以将这些属性保存在缓冲区中,如下所示:
const propsPerObject = 4; // 4 values per Cell object, since index property can be calculated. Nothing stops you from saving them though
const numberOfObjects = 10; // max number of Cell objects which buffer could contain
const bytesPerProperty = 1; // depends on how big should numbers be in Cell instances. Check TypedArray reference to choose required size
const bytes = propsPerObject * bytesPerProperty * numberOfObjects;
const buffer = new ArrayBuffer(bytes);
const int8 = new Int8Array(buffer); // I used this type according to bytesPerProperty variable
//write data for the third "object":
const index = propsPerObject * 3;
int8[index] = 0; // m property
int8[index + 1] = -1; // n property and so on...
I suggest you should create a class which will handle things such read/write etc. This wouldn't work with reference properties, though.我建议您应该创建一个 class 来处理诸如读/写等事情。不过,这不适用于引用属性。
PS: instatiation of ArrayBuffer with huge number of elements can create an out of memory exception more easily than typical arrays. PS:具有大量元素的 ArrayBuffer 实例化可以比典型的 arrays 更容易创建 out of memory 异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.