数组冷知识

153 阅读2分钟

数组的最大长度

数组最大可以存储 2^32 个值,因此length最大值为 2^32 - 1

number 最大值为 2^53 -1, 遵循IEE 754规范,使用 64bit位存储二进制数据,其中 1 位符号位,11 位指数位,又因为最后一位固定为 1,可以省略,因此最大值为2^53 -1

为什么数组可以存储任意类型

这里引用大佬的话:


// The JSArray describes JavaScript Arrays

// Such an array can be in one of two modes:

// - fast, backing storage is a FixedArray and length <= elements.length();

// Please note: push and pop can be used to grow and shrink the array.

// - slow, backing storage is a HashTable with numbers as keys.

class JSArray: public JSObject {

public: // [length]: The length property.

DECL_ACCESSORS(length, Object)

// 。。。此处省略实现

// Number of element slots to pre-allocate for an empty array.

static const int kPreallocatedArrayElements = 4;

};

可以看出 JSArray 是继承自 JSObject 的,所以在 JavaScript 中,数组可以是一个特殊的对象,内部也是以 key-value 形式存储数据,所以 JavaScript 中的数组可以存放不同类型的值。

似懂非懂,有大佬解释下吗?

数组的存储方式

两种实现模式:

快数组

  • 可以使用索引直接定位,使用连续的内存空间,当数组满的时候,继续push时自动进行扩容.

  • 是数组创建的默认模式.

慢数组

  • 以哈希表的形式存储在内存空间里,维护一个哈希表,不需要开辟连续的内存空间,与快数组相比性能较差

快数组与慢数组之间的转换

  • 当快数组新加入的索引相比之前容量的差值>=1024

  • 快数组新容量是扩容后容量的三倍之多时

数组的扩容以及缩容

扩容

  • 申请 new_capacity = old_capacity / 2 + old_capacity + 16 长度的空间

  • 将数组拷贝到新内存中

  • 将新元素放置在末尾位置

  • 数组的 length + 1 并返回

缩容

时机: 当数组元素减少后, 如果数组的容量大于等于 length 的两倍,则进行缩容操作,