简体   繁体   English

JavaScript(或 NodeJS)如何处理内存分配?

[英]How does JavaScript(or NodeJS) handle memory allocation?

Assume V8 context.假设 V8 上下文。

Lets say an element of Number type has a size of 4 bytes.假设Number类型的元素大小为 4 个字节。

Now, if I have an array,现在,如果我有一个数组,

let a = [1,2,3,4,5];

Logically speaking, the starting addresses of blocks for each element should be 1000,1004,1008,1012,1016按理来说,每个元素的块起始地址应该是1000,1004,1008,1012,1016

Now, lets say we have a string TestString which takes 10 bytes, and I do:现在,假设我们有一个需要 10 个字节的字符串TestString ,我这样做:

a[2] = 'TestString';

Such that the array becomes [1,2,'TestString',4,5] .这样数组就变成了[1,2,'TestString',4,5]

How does JS handle the memory allocation of TestString and managing the address space of blocks in the array? JS如何处理TestString的内存分配和管理数组中块的地址空间?

An array in JavaScript is really just a special type of object. JavaScript 中的数组实际上只是一种特殊类型的对象。 As such, the "indexes" of the array are really just properties storing an integer value, and the data being stored are just pointers to the allocated memory blocks-- very much like a linked list.因此,数组的“索引”实际上只是存储整数值的属性,存储的数据只是指向分配的内存块的指针——非常像链表。

This is why you can use array methods like push or pop on the existing array without re-allocating the block of memory set aside for the array.这就是为什么您可以在现有数组上使用 push 或 pop 等数组方法,而无需重新分配为数组预留的内存块。

I don't know the exact details of what V8 is doing, but I'm going to assume because of JavaScript's loosely/dynamically typed nature, it's probably not allocating memory contiguously like you used in your example-- there are just too many potential drawbacks to that for such a weak and dynamically typed language.我不知道 V8 正在做什么的确切细节,但我假设由于 JavaScript 的松散/动态类型性质,它可能不会像您在示例中使用的那样连续分配内存——有太多的潜力这种弱动态类型语言的缺点。

JavaScript basically makes everything an object. JavaScript 基本上使一切成为对象。 An array is an object, the index values of the array, just pointers to objects.一个数组就是一个对象,数组的索引值,只是指向对象的指针。 Which is why every data type is a variable and has access to properties and methods.这就是为什么每种数据类型都是变量并且可以访问属性和方法的原因。

In reality, the address spaces of:实际上,地址空间为:

let a = [1, 2, 3, 4, 5];

Would be pointers to the allocated memory blocks such as 548995, 48885, 3889282, 093838, 7883344. Or something like that.将是指向分配的内存块的指针,例如 548995、48885、3889282、093838、7883344。或类似的东西。 When you re-allocate any of them, JavaScript will find a block of memory in the heap and set the array index value to the allocated block's pointer.当你重新分配它们中的任何一个时,JavaScript 将在堆中找到一块内存并将数组索引值设置为分配块的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM