I want to make a random generator for javascript for thousands of objects, but it's being extremely slow. Is there a better way to use Math.random()
so that I only need to call it once?
Asked
Active
Viewed 1,383 times
1

Corbbin Goldsmith
- 387
- 1
- 3
- 9
-
Make a seed, then use a typed array and a custom function to generat random numbers inside that buffer? Just an idea, I don't have a working example. – trusktr Mar 07 '16 at 00:29
-
1"extremely slow"? Ballpark speaking, what is _extremely_ slow in this case? Here is a demo with 50k iterations, generating a random number. Looks okay to me - [jsfiddle link](https://jsfiddle.net/ynsmfm6t/) – scniro Mar 07 '16 at 00:35
-
50k iterations at 60fps on a 6 year old computer... 50,000 x 60 x 6 = slow – Corbbin Goldsmith Mar 07 '16 at 00:40
-
what does fps have to do with it? That analysis doesn't make sense. If you're painting to the screen and it's slow, perhaps specify. Doubt the random number generation has much to do with it – scniro Mar 07 '16 at 00:58
1 Answers
0
Short answer, you can't. But that's not an informative nor useful answer.
Long answer: You can't but you can use some tricks
There are several ways you can make tricks
- Use a more naive pseudo random number generator. You can use XorShift or similar tricks, but your performance can vary, you can test here.
- Get more than one number for a single
Math.random()
shot. You say you need to feed 'thousands' of objects. From here, the precision seems enough with numbers like0.0076860846020281315
giving you 20 digits. If you have 10,000 objects to fill with a single digit, you can easily fill 20 with a singleMath.random()
this will reduce the function calls. - Generate them offline, then fill.

Ariel M.
- 896
- 8
- 24
-
I'll be using an array of random numbers, and then cycle through it. It should be random enough to get the job done. Thansk. – Corbbin Goldsmith Mar 07 '16 at 00:39