DEV Community

Cover image for Speed Up Your Javascript With These Simple Methods
Code_Jedi
Code_Jedi

Posted on

Speed Up Your Javascript With These Simple Methods

If your Javascript code is running slower than you'd like, or if you just want to know how to make your code faster regardless, stick around for some easy to implement ways of making your Javascript run faster

Bottom of Webpage

To make your webpage's loading faster, make sure your Javascript code is at the bottom of your HTML webpage's body tag.

Web Workers

If your webpage uses time-intensive Javascript operations, web workers can save you a lot of time. Using web workers can mean the difference between an unresponsive and slow webpage, and a smooth running and fast webpage.

Web workers are separate threads created by your main Javascript code to work in parallel with the main process.
You can read about web workers and their JS implementation here

Saving DOM Elements

When manipulating the same DOM element multiple times, to speed up your code, you should define it once and then keep referencing it.
No

const el1 = document.getElementById("demo");
el1.style.color = "green";

const el1 = document.getElementById("demo");
el1.style.color = "blue";

const el1 = document.getElementById("demo");
el1.style.color = "pink";
Enter fullscreen mode Exit fullscreen mode

Yes

const el1 = document.getElementById("demo");
el1.style.color = "green";

el1.style.color = "blue";

el1.style.color = "pink";
Enter fullscreen mode Exit fullscreen mode

Reduce Library Dependancies

Loading libraries in JS can take up a lot of time, make sure to remove any unneeded library dependancies in your Javascript code.

Reduce Loop Activity

In Javascript, loops can take quite a lot of time to finish running. A simple way to make your JS loops run faster is by defining the loop parameters before the loop itself.
No

for (let g = 0; g < arr.length; g++) {
Enter fullscreen mode Exit fullscreen mode

Yes

let arrlen = arr.length;
for (let g = 0; g < arrlen; g++) {
Enter fullscreen mode Exit fullscreen mode

This will speed up your for loop because now, instead of getting the length of the "arr" array every single iteration, it will get that value once and reuse it throughout every iteration.

Avoid Global Variables

Global variables can slow down your JS code. When defining a variable for the first time, make sure to add the var prefix to make it a local variable instead of a global one.
No

v1 = 9
Enter fullscreen mode Exit fullscreen mode

Yes

var v1 = 9
Enter fullscreen mode Exit fullscreen mode

Conclusion

I hope that these were helpful.

Discussion (7)

Collapse
frankwisniewski profile image
Frank Wisniewski • Edited on

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)

Collapse
hyrumwhite profile image
hyrumwhite

For that last one, it depends on where you're creating your variable. You declared a global variable in both cases if you're in the global context. Also, globals dont slow down code. They can make understanding and maintaining your code more difficult if used improperly.

Collapse
cavazzatommaso profile image
cavazzatommaso

I have a question about the reduce loop activity. Why it's not the same using array.length or a local variable? Array.length is not a method so why there will be less activity?

Collapse
dgx32123 profile image
Dominik Gorczyca

Because code needs to look for property every time for loop iterates and then send the property value, when you store the result of Array.length, it's just a number, your code doesn't need to look for anything, it can just pass the value.
That's why it faster, I am not sure if the speed difference matters that much. Probably not.