LoginSignup
7
0

More than 5 years have passed since last update.

JavaScript の pop と shift の速度差

Last updated at Posted at 2018-11-29

概要

JavaScript の Array にある shiftpop の速さってどれぐらい違うのか、という話が某所で出たので、適当に測ってみた。

結論

ブラウザによっていろいろだけど、やっぱり pop のほうが速い。

測定方法

以下の2つのソースをブラウザの開発者機能(?)のコンソールに貼り付けて何が出るかを調査した。

なんか var が無いとかセミコロンがないとか、いろいろ残念なソースだけど気にしない。

shift.js
a=[1]
while( a.length<100000 ){
  a = a.concat(a);
}
t0=performance.now();
while( 0<a.length ){
  a.shift();
}
t1=performance.now();
t1-t0;
pop.js
a=[1]
while( a.length<100000 ){
  a = a.concat(a);
}
t0=performance.now();
while( 0<a.length ){
  a.pop();
}
t1=performance.now();
t1-t0;

測定結果

マシンは MacBook Pro (Retina, 15-inch, Mid 2015)。
OS は macOS Mojave 10.14.1。

ブラウザ shift pop shift÷pop
Chrome70 2788 11 253
Opera57 2782 11 253
Firefox63 52 45 1.2
Safari12 10 3 3.3

続いて IE と Edge のために今は亡き thinkpad 13 で。
Windows 10 pro 64bit version 1809

ブラウザ shift pop shift÷pop
Chrome70 2138 18 121
Firefox63 58 54 1.1
Edge 3066 525 5.8
IE11 959 39 25

で。

  • Chrome と Opera は同じ感じ。shiftpop に比べてすごく遅い。C++ のvector とかと同じ感じなのかな。
  • Firefox は、shift÷pop がほぼ 1 ということで、shift しても先頭を指すポインタが動くだけとか、そういう実装になっているに違いない。
  • Safari は shift÷pop が 3.3。どんなデータ構造を採用したらこうなるんだろうか。謎。すごく速いのも気になる。
  • IE と Edge のアルゴリズムは違うみたい。意外に IE の方が速かった。
7
0
0

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