什么是在JavaScript中生成随机整数的最快方法? [英] What is the fastest way to generate a random integer in javascript?
问题描述
Math.random();通常情况下,这是如何在javascript中获得一个随机数。
然而这个方法在生成随机整数方面似乎效率不高。
首先,随机函数必须产生一个随机的小数点,如<0.1036098338663578 ,然后它必须乘以一个合适的范围(< I> 10.464593220502138 的)。最后,floor函数减去小数以产生结果(在这种情况下,是10)。
var random_integer = Math.floor(Math.random()* 101);
有没有更快的方式在javascript中产生随机整数?
$ h $>编辑1:
我用这个来创建一个画布HTML5游戏。 FPS约为50,除了生成一个随机数之外,我的代码已经非常优化了。
$ p> var random_integer = Math.random()* 101 | 0;
尽管如此,它仍然不适用于庞大的数字。
(并且运行速度不会更快,至少不会在chrome中)。
您可以实现如果你事先产生了随机数,游戏速度要快得多。
for(var i = 1e6,lookupTable = []; i--;){
将会旋转通过一个具有一百万个随机整数的数组。与调用
lookupTable.push(Math.random()* 101 | 0);
函数lookup(){
return ++ i> = lookupTable.length? lookupTable [i = 0]:lookupTable [i];
code $
$ c $ lookuprandom
和快得多 > floor
(当然,从生成查询表开始,会有一个加载时间的惩罚)。Normally this is how you get a random number in javascript.
Math.random();
However this method seems to be inefficient when it comes to generating random integers.Firstly, the random function has to generate a random decimal, like 0.1036098338663578, then it has to be multiplied to a suitable range (10.464593220502138). Finally, the floor function subtracts the decimals to produce the result (which in this case, 10).
var random_integer = Math.floor(Math.random()*101);
Is there a faster way to generate random integers in javascript?
Edit1:
I am using this for creating a canvas HTML5 game. The FPS is about 50, and my code is pretty optimized, apart from generating a random number.
解决方案This code is faster... to type.
var random_integer = Math.random()*101|0;
It won't work right for huge numbers though.
(and it doesn't run any faster, at least not in chrome.)
You could achieve a much faster speed during the game if you generate the random numbers beforehand, though.
for (var i=1e6, lookupTable=[]; i--;) { lookupTable.push(Math.random()*101|0); } function lookup() { return ++i >= lookupTable.length ? lookupTable[i=0] : lookupTable[i]; }
lookup
will rotate through an array with a million random integers. It is much faster than callingrandom
andfloor
(of course, there is a "loading time" penalty up front from generating the lookup table).这篇关于什么是在JavaScript中生成随机整数的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!