LoginSignup
2
1

More than 3 years have passed since last update.

[JavaScript] 擬配列オブジェクトから配列を作る最適解の考察(スプレッド演算子 vs Array.from())

Last updated at Posted at 2019-05-21

概要

  • 「配列型」や「反復型」の擬配列オブジェクトから配列のインスタンスを作る機会が多いので、最適解が何かを調べてみました。

方法

  • 構文が分かりやすい以下のコードのどちらが速いかを比較してみました。回転数は 100万回。実行環境は Google Chrome 74.0.3729.169 です。
[...xxx]
const max = 1000000
console.time()
for (let i = 0; i < max; ++i) {
  const a = [...document.body.childNodes]
}
console.timeEnd()
Array.from(xxx)
const max = 1000000
console.time()
for (let i = 0; i < max; ++i) {
  const a = Array.from(document.body.childNodes)
}
console.timeEnd()

結果

  • スプレッド演算子がかなり速いようです。構文としてもスマートなので、こっちを使っていこうと思います。
statement Google Chrome
74.0.3729.169
Safari
12.1
[...xxx] 11421.31689453125ms 649.917ms
Array.from(xxx) 16186.26708984375ms 678.806ms
  • もっと速いのがある場合は、コメント欄で教えて下さい!

学習

日本語 英語
配列型 array-like arugments
NodeList
反復型 iterable Map
Set
String
2
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1