且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript中是否有一种方法可以在相对较快的时间内获得很大数量的BigInt类型的表示?

更新时间:2023-02-19 23:15:29

该数字(或仅其前10位数字)的输出花费那么多时间的主要原因是该数字必须转换为十进制表示形式.这是一个巨大的计算,涉及数以千计的字节的移位,大数的减法,通过多个字节的龋齿以及所有重复的数千次.

The main reason why the output of the number (or only its first 10 digits) takes that much time is that the number must be converted to a decimal representation. This is a huge calculation, involving shifts of many thousands of bytes, subtractions of big numbers, with a cary passing through that many bytes, and all that repeated thousands of times.

如果将输出代码替换为:

If you replace the outputting code with:

result.toString(2).slice(0, 10)
//             ^^

...您会发现速度有了极大的提高.原因是此操作不需要基本转换,并且可以线性时间(以字节数为单位)构建字符串.

... you'll see a drastic improvement in speed. The reason is that for this operation no base conversion is needed, and the string can be built in linear time (in terms of the number of bytes).