惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Vercel News
Vercel News
T
Tor Project blog
博客园_首页
F
Fortinet All Blogs
V
V2EX
雷峰网
雷峰网
Microsoft Azure Blog
Microsoft Azure Blog
Y
Y Combinator Blog
博客园 - 【当耐特】
Jina AI
Jina AI
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
Engineering at Meta
Engineering at Meta
Spread Privacy
Spread Privacy
C
Cyber Attacks, Cyber Crime and Cyber Security
The Cloudflare Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Apple Machine Learning Research
Apple Machine Learning Research
V2EX - 技术
V2EX - 技术
Latest news
Latest news
L
LINUX DO - 最新话题
IT之家
IT之家
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - 叶小钗
博客园 - Franky
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
博客园 - 聂微东
MyScale Blog
MyScale Blog
S
Security @ Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
小众软件
小众软件
S
Secure Thoughts
D
Darknet – Hacking Tools, Hacker News & Cyber Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
有赞技术团队
有赞技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Vulnerabilities – Threatpost
T
Tailwind CSS Blog
L
Lohrmann on Cybersecurity
T
Troy Hunt's Blog
美团技术团队

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
How To Accelerate the JavaScript Spread Operator
Dmitri Pavlutin · 2019-09-03 · via Dmitri Pavlutin Blog

In this post, you will read an interesting investigation on how to boost the performance of the spread operator.

Let's start with a short introduction on how spread operator works inside array literals.

The spread operator, or three dots, takes an array or generally an iterable [...arrayOrIterable] and slices it into pieces. Then the array literal uses these pieces to construct a new array.

The spread operator can be placed at any position inside the array literal:


const numbers = [1, 2, 3];

[0, ...numbers]; // => [0, 1, 2, 3]

[0, ...numbers, 4]; // => [0, 1, 2, 3, 4]

[...numbers, 4]; // => [1, 2, 3, 4]


Now comes the interesting question. Is there a position of the spread operator inside the array literal that could increase performance? Let's find out.

1. Append to head and to tail functions

Before starting the performance comparisons, let's define two functions.

The first one is appendToTail():


function appendToTail(item, array) {

return [...array, item];

}

const numbers = [1, 2, 3];

appendToTail(10, numbers); // => [1, 2, 3, 10]


appendToTail() inserts the item at the end of the array. This function uses [...array, item].

The second one is appendToHead():


function appendToHead(item, array) {

return [item, ...array];

}

const numbers = [1, 2, 3];

appendToHead(10, numbers); // => [10, 1, 2, 3]


appendToHead() is a pure function that returns a new array where the item is appended at the head of the original array. It uses [item, ...array].

At first sight, there's no reason to think that these functions perform differently. But let's take a try.

2. The performance test

Let's run the performance test of [...array, item] vs [item, ...array] on a MacBook Pro laptop in the following 3 browsers:

  • Chrome 76
  • Firefox 68
  • Safari 12.1

Here are the performance test results:
Spread operator performance check

As expected, in Firefox and Safari browsers [...array, item] and [item, ...array] have the same performance.

In Chrome, however, [...array, item] performs twice faster than [item, ...array]. That's a useful result.

To accelerate the performance of spread operator in Chrome, use the spread operator at the beginning of the array literal:


const result = [...array, item];


But another question arises: why does it happen?

3. The fast-path optimization

Starting the version 7.2 of the V8 engine (that powers the JavaScript execution in Chrome) a new optimization of the spread operator is available: the fast-path optimization.

In a few sentences, it works as follows.

Without this optimization, when the engine encounters a spread operator [...iterable, item], it invokes the iterator (iterator.next()) of the iterable object. On each iteration, the memory of the resulted array is increased, and the iteration result is added to it.

But the fast-path optimization detects a known iterable (like an array of integers) and skips the creation of the iterator object at all. Then the engine reads the length of the spread array, allocating only once memory for the resulted array. Then passes by index the spread array, adding each item to the resulted array.

The fast-path optimization skips the creation of the iteration object, allocating the memory for the result only once. Thus the performance increase.

4. Supported data structures

The fast-path optimization applies to the following standard JavaScript data structures.

Arrays


const numbers = [1, 2, 3, 4];

[...numbers, 5]; // => [1, 2, 3, 4, 5]


Strings


const message = 'Hi';

[...message, '!']; // => ['H', 'i', '!']


Sets


const colors = new Set(['blue', 'white']);

[...colors, 'green']; // => ['blue', 'white', 'green']

[...colors.values(), 'green']; // => ['blue', 'white', 'green']

[...colors.keys(), 'green']; // => ['blue', 'white', 'green']


Maps

On maps only map.keys() and map.values() methods are supported:


const names = new Map([[5, 'five'], [7, 'seven']]);

[...names.values(), 'ten']; // => ['five', 'seven', 'ten']

[...names.keys(), 10]; // => [5, 7, 10]


5. Conclusion

When the spread array is located at the beginning of the array literal, you can get a performance boost due to the fast-path optimization. It is available in V8 engine v7.2 (shipped in Chrome v72 and NodeJS v12).

With this optimization, the performance test shows that [...array, item] can perform at least twice faster than [item, ...array].

Note that while fast-path is indeed useful, you might want to use it in places where the performance is important, or if you'll dealing with large arrays.

Otherwise, in most situations, don't force the optimization since the end-user most likely will not feel the difference.

What interesting performance optimizations in JavaScript do you know?