- read

Internal Implementation of JavaScript Arrays

Xiuer Old 71

Internal Implementation of JavaScript Arrays

Xiuer Old
JavaScript in Plain English
8 min read14 hours ago

--

Each JS execution engine has its own implementation. This time we focus on how the V8 engine implements arrays.

The main article to read this week is How JavaScript Array Works Internally?, which briefly introduces the array implementation mechanism of the V8 engine. The author will also refer to some other articles and combine it with the source code to explain.

Overview

There are many patterns for the internal types of JS arrays, such as:

  • PACKED_SMI_ELEMENTS
  • PACKED_DOUBLE_ELEMENTS
  • PACKED_ELEMENTS
  • HOLEY_SMI_ELEMENTS
  • HOLEY_DOUBLE_ELEMENTS
  • HOLEY_ELEMENTS

PACKED is translated as packed, and the actual meaning is “array with continuous values”; HOLEY is translated as hole, which means that this array has many invalid items like holes, and the actual meaning is “array with holes in the middle”. These two nouns are mutually exclusive. of.

SMI indicates that the data type is a 32-bit integer, DOUBLE indicates a floating point type, and no type is written. The type of array is also mixed with strings, functions, etc., and the description at this position is also mutually exclusive.

So you can look at the internal type of the array like this: [PACKED, HOLEY]_[SMI, DOUBLE, '']_ELEMENTS.

The most efficient type PACKED_SMI_ELEMENTS

A simplest empty array type defaults to PACKED_SMI_ELEMENTS:

const arr = [] // PACKED_SMI_ELEMENTS

The PACKED_SMI_ELEMENTS type is the best performing mode, and the stored type is a continuous integer by default. When we insert an integer, V8 will automatically expand the array. At this time, the type is still PACKED_SMI_ELEMENTS:

const arr = [] // PACKED_SMI_ELEMENTS
arr.push(1) // PACKED_SMI_ELEMENTS

Or directly create an array with content, which is also of this type:

const arr = [1, 2, 3] // PACKED_SMI_ELEMENTS

Automatic downgrade