1
0

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 1 year has passed since last update.

BigInt と Number の速度差

Posted at

これは何?

JavaScript で使えるようになった多倍長整数。
計算の速さがどうなのか知りたいので調べてみた。

というわけで、今日も楽しいマイクロベンチマーク。

計算内容

足し算、掛け算、割り算、ビット計算、なんかを交えてこんな感じ。

JavaScript
const bi=(a0,b0)=>{
    const a = BigInt(a0);
    const b = BigInt(b0);
    let n=0n;
    for( let i=0n ; i<10000000n ; ++i ){
        n += a;
        n <<= 2n;
        n *= b;
        n /= 3n;
        n &= 0x1fffffffn;
        n >>= 1n;
    }
    return n;
};

const nu=(a,b)=>{
    let n=0;
    for( let i=0 ; i<10000000 ; ++i ){
        n += a;
        n <<= 2;
        n *= b;
        n /= 3;
        n &= 0x1fffffff;
        n >>= 1;
    }
    return n;
};

const measure = (name, x)=>{
    const t0 = performance.now();
    const v = x(5683,1237);
    const t1 = performance.now();
    console.log(name, v, t1-t0);
};

measure("bigint", bi);
measure("number", nu);
measure("bigint", bi);
measure("number", nu);
measure("bigint", bi);
measure("number", nu);

実行結果

手元は MacOS Ventura 13.4 / Apple M1 Pro 非MAX

掲載は最後の 1回ずつ。

node

node v20.3.0。

bigint 28771428n 502.7227920293808
number 28771428 135.35170805454254

Chrome

バージョン: 114.0.5735.133(Official Build) (arm64)

bigint 28771428n 459.8999999985099
number 28771428 135.5

Edge

バージョン 113.0.1774.57 (公式ビルド) (arm64)

bigint 28771428n 439.30000000447035
number 28771428 139.60000000149012

Firefox

114.0.1 (64 ビット)

bigint 28771428n 253
number 28771428 136

Safari

バージョン16.5 (18615.2.9.11.4)

bigint – 28771428n – 2328
number – 28771428 – 162.00000000000182

まとめ

差が小さい Firefox でも倍ぐらい Number が速い。
V8 陣営(Node, Chrome, Edge)は 3倍ちょっと Number が速い。
Safari では 10倍以上 Number が速い と大きく差がついた。

この計算内容で、Number より BigInt が速い理由は思いつかないので、単に計算時間を短くする努力をたくさんやっているかどうかの違いだと思う。

まあ思うだけだけど。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?