Demystifying JavaScript Array Internals ??
Arrays are a fundamental data structure in JavaScript. Behind the scenes, V8 - Google's JavaScript engine - optimizes arrays in two main ways:
?? Contiguous Arrays: For densely populated arrays without undefined elements, V8's magic comes alive. Elements are stored consecutively, leading to faster access, efficient memory usage, and cache-friendly performance. ??
This provides several benefits:
V8 uses this representation when:
For example:
const arr = [1, 2, 3, 4];
This array will be stored as a contiguous array
Contagious Array is further divided into different types based on what data is and where it is in the array.
const array=[1,2,3,4]
const array=[1,2,3,4,6.0,]
const array=[1,2,3,4,6.0,'a']
PACKED_SMI >>> PACKED_DOUBLE >> PACKED_ELEMENTS
领英推荐
Holey Arrays
??? Holey Arrays: When your array has undefined elements, V8 resorts to holey arrays. Elements aren't stored contiguously, and "holes" represent the undefined elements. Accessing elements may be a tad slower than contiguous arrays. This means:
This allows V8 to:
For example:
const arr = [1, <3 empty items>, 3];
This array will be stored as a holey array, with the undefined element represented as a hole.
When accessing elements by index, V8 must check for holes and return undefined appropriately. This makes accessing elements slightly slower than in contiguous arrays.
HOLES ARE VERY VERY EXPENSIVE IN JS
Holey array is categorised in further types as
const array=[1,2,3,<1 empty value>,4]
const array=[1,2,3,<1 empty value>,4,6.0,]
const array=[1,2,3,<1 empty value>,4,6.0,'a']
HOLEY_SMI >>> HOLEY_DOUBLE >> HOLEY_ELEMENTS
Optimization
? Optimization: V8 continuously fine-tunes arrays based on their usage. As arrays transition from holey to contiguous, V8 works its magic to optimize the representation.
?? Pro Tip: Leverage built-in JavaScript methods like .map and .filter for top-notch performance. The JavaScript engine knows best! ??
useAbout((skills) => skills?.javascript?.reactjs?.nextjs);
1 年Video - https://www.youtube.com/watch?v=ZRS485LxX0s Hasnode Article - https://gyandeeparyan.hashnode.dev/interesting-internals-of-array-in-javascript