DEV Community

Discussion on: Speed Up Your Javascript With These Simple Methods

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited

Reduce Loop Activity

You should try it yourself. If it's faster at all, we're moving in the realm of micro-optimization

<!DOCTYPE html>
<html lang=de>
  <meta charset=UTF-8>
  <title>Document</title>

  <button id=start>start</button>

  <script>
  "use strict";

  const size = 10_000_000
  const myArray = new Array( size )
  for( let i = 0; i < size; i++ ){
    myArray[i] = i+1
  }

  const measure = () => {
    let arrlen = myArray.length;
    let start1 = performance.now()
      for ( let i = 0; i < arrlen; i++ ) {}
    let end1 = performance.now()

    let start2 = performance.now()
      for ( let i = 0; i < myArray.length; i++ ) {}
    let end2 = performance.now()

    console.log( end1 - start1 )
    console.log( end2 - start2 )
  }

  start.onclick = measure

  </script>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bradtaniguchi profile image
Brad

I'm confused about how this works. On my end it looks like the 1 metrics (which are supposedly faster) returns a larger number than the 2 metrics?

I was getting values similar to:

400
50
Enter fullscreen mode Exit fullscreen mode

How and why?

Collapse
 
frankwisniewski profile image
Frank Wisniewski

That's why I wrote, if it's faster at all...

Thread Thread
 
bradtaniguchi profile image
Brad

Yea I noticed that and wanted more insight, so I dug into it more.

It would appear the execution speed is affected by the order/definition.

I saw improvements when flipping the order of execution where the "faster" method goes second, rather than first and the execution ends up faster. I'm not really sure why this is.

I also removed the slower/faster pieces of code so the code only focuses on only 1 implementation and got similar behavior where the faster version does go faster, but only a little.

So end all, yes the "faster" optimization is an optimization. But even then you're only looking at slightly faster execution speeds in the realm of .05 of a second improvements for 10 million elements. (at least on my machine)