js-framework-benchmark icon indicating copy to clipboard operation
js-framework-benchmark copied to clipboard

Why Math.random() * 1000?

Open greggman opened this issue 3 years ago • 4 comments

Why this

function random(max) {
  return Math.round(Math.random() * 1000) % max;
}

Instead of this

function random(max) {
  return Math.random() * max | 0;
}

PS: This is a genuinely curious question. It seems like rand * 1000 % max has issues like for one, if max is > 1000, and for 2 unequal distribution but maybe you chose it for some other reason which is why I asked.

greggman avatar Dec 23 '20 02:12 greggman

Long time that I didn't take time for this bug report. Well, this had been in place since the second commit and I had never thought about it. I tried for a few frameworks - for most frameworks it looks like it doesn't change much, but for react it really makes a difference: Except react hooks I'd say they are within the precision of the new random function is negligible faster for create row, update all rows and create many rows (i.e. those benchmarks that call random often). React hooks is really a strange one and I have no idea why select row and partial update (both benchmarks that don't call random) differ. I ran react twice and both runs looked that way.

Has anyone an idea why it might impact these two benchmarks for react?

krausest avatar May 02 '21 20:05 krausest

I'm just thinking out loud without looking at the code. random() * 1000 % max will never make value greater than 1000 so if you're picking from 1000000 random things only the first 1000 will ever be accessed. If there is any kind of caching going on in react then you're more likely to get a cache hit the smaller the number of items you select from.

greggman avatar May 03 '21 13:05 greggman

Yes, you're right. The random value is used to build strings from three arrays ${A[random(A.length)]} ${C[random(C.length)]} ${N[random(N.length)]}. The arrays are pretty short (A 25,B 11 and C 13 elements), so we're never cutting elements off. The distribution of the random numbers might indeed be negatively impacted such that they might not be evenly distributed. I'm just surprised that it impacts two benchmarks that don't use the random function directly and should only use the key of the element which hasn't anything to do with the random function either.

krausest avatar May 03 '21 15:05 krausest

Some more react frameworks with the other random function. So far only react-hooks differs for the new random function. All others are close enough not to matter.

krausest avatar May 03 '21 19:05 krausest