acr*_*ing 5 javascript node.js
我想使用Number.toString(62),但 ECMAScript 不支持它(仅支持从 2 到 36 的基数),所以我正在编写自己的Number.toString.
而我只需要用它来格式化int64,不需要关心double。
因此,我Number对BigInt不同radix.
基准代码如下:
\n\nimport { Suite } from \'benchmark\';\nimport { shuffle } from \'lodash\';\n\nconst float = new Array(10000)\n .fill(0)\n .map(() => Math.random() * Number.MAX_SAFE_INTEGER);\nconst int = float.map(Math.floor);\nconst big = int.map(BigInt);\n\nexport const suite = new Suite(\'native integer format\')\n .add(\'Int64.toString(10)\', () => shuffle(int).map((n) => n.toString(10)))\n .add(\'Int64.toString(16)\', () => shuffle(int).map((n) => n.toString(16)))\n .add(\'Int64.toString(36)\', () => shuffle(int).map((n) => n.toString(36)))\n .add(\'Float64.toString(10)\', () => shuffle(float).map((n) => n.toString(10)))\n .add(\'Float64.toString(16)\', () => shuffle(float).map((n) => n.toString(16)))\n .add(\'Float64.toString(36)\', () => shuffle(float).map((n) => n.toString(36)))\n .add(\'BigInt.toString(10)\', () => shuffle(big).map((n) => n.toString(10)))\n .add(\'BigInt.toString(16)\', () => shuffle(big).map((n) => n.toString(16)))\n .add(\'BigInt.toString(36)\', () => shuffle(big).map((n) => n.toString(36)))\n .add(\'Date.now()\', () => shuffle(int).map(Date.now));\nRun Code Online (Sandbox Code Playgroud)\n\n结果是:
\n\nnative integer format -> Int64.toString(10) x 660 ops/sec \xc2\xb12.82% (83 runs sampled)\nnative integer format -> Int64.toString(16) x 109 ops/sec \xc2\xb10.66% (79 runs sampled)\nnative integer format -> Int64.toString(36) x 134 ops/sec \xc2\xb10.42% (84 runs sampled)\nnative integer format -> Float64.toString(10) x 448 ops/sec \xc2\xb12.49% (85 runs sampled)\nnative integer format -> Float64.toString(16) x 103 ops/sec \xc2\xb11.15% (75 runs sampled)\nnative integer format -> Float64.toString(36) x 130 ops/sec \xc2\xb11.36% (83 runs sampled)\nnative integer format -> BigInt.toString(10) x 424 ops/sec \xc2\xb10.64% (92 runs sampled)\nnative integer format -> BigInt.toString(16) x 1,039 ops/sec \xc2\xb11.86% (92 runs sampled)\nnative integer format -> BigInt.toString(36) x 532 ops/sec \xc2\xb10.76% (92 runs sampled)\nnative integer format -> Date.now() x 1,163 ops/sec \xc2\xb10.59% (93 runs sampled)\nRun Code Online (Sandbox Code Playgroud)\n\n正如您所看到的,BigInt.toString(16)是最快的(除了 Date.now,它是要引用的对象)。
我的性能比 快一点Int64.toString。
是否有任何开源代码或已知算法可以加速它?
\n\n还有一些有趣的事情:其中最快的Number.toString(radix)是Number.toString(10),但它是toString(16)针对 的BigInt。这是魔法吗?