1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【javascript】unshiftが遅い

Last updated at Posted at 2021-07-12

#遅くなる時
自分用に作った関数のテスト中に、for10000回ほどunshiftを用いて処理した時、明らかに重くなった。

#コード
case2のように別の配列を用意してpushで追加してから反転させてunshiftすれば
pushと同程度の処理時間で済む。
大量に処理する時以外は普通にunshiftを使ったほうが良いと思う。

const n = 10000;

//【case1】
//直接unshift
console.time('unshift');

const base1 = Array(10).fill(0);

for (let i=0; i<n; i++) {
	base1.unshift(i);
}

console.timeEnd('unshift');
//console.log(base1);

//【case2】
//空の配列にpushでまとめた後に反転させてunshift
console.time('push');

const base2 = Array(10).fill(0);

const arr = [];
for (let i=0; i<n; i++) {
	arr.push(i);
}
base2.unshift(...arr.reverse());

console.timeEnd('push');
//console.log(base2);
1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?