Here is the code:

const startTime = new Date().getTime(); const arr = []; for (let i = 0; i < 10000000; ++i) { arr.push(Math.random()); } console.log(new Date().getTime() - startTime); 

Is it possible to optimize it somehow? Now it runs for about 300ms. Tried to compile the source code of the nodejs itself. It did not help

Are there any other ways to accelerate?

P.S. Yes, the code looks meaningless. But it is he who needs to be optimized.

  • If in your opinion this code is no longer optimized. Then please write about this. It is important for me to know. What is the best version of this code or can it be improved yet. - Mister X
  • 2
    From what point of view do you want to optimize it? In terms of performance? - Stepan Kasyanenko
  • Yes. Whatever he worked out as quickly as possible - Mister X
  • Thank you Stepan Kasyanenko. His method works out for 200ms. Maybe something else can be done? - Mister X
  • one
    Thank you is accepted in the form of an accepted answer) But I don’t think that it can be somehow faster, because we run into the speed of Math.random() - Stepan Kasyanenko

1 answer 1

You can speed up the execution time a bit if you pre-set the size of the array.

 let startTime = null; const cnt = 10000000; console.time('first'); const arr2 = new Array(cnt); for (let i = 0; i < cnt; ++i) { arr2[i] = Math.random(); } console.timeEnd('first'); console.time('second'); const arr = []; for (let i = 0; i < cnt; ++i) { arr.push(Math.random()); } console.timeEnd('second');