DEV Community

loading...
Cover image for Avoid slow Javascript code

Avoid slow Javascript code

Oscar Pacheco Ortiz
Full-Stack Web Deveoloper by day / Game developer by night
Updated on ・4 min read

Table of contents

Introduction

In this article, we will discuss a few topics that can help your Javascript code perform well and fast. We will be going over some common mistakes to help us understand what makes our code run smoother and a bit more efficient. Later on we will discuss about Algorithms and Data structures, but that is a little more advanced. So for starters, let us first learn the common mistakes that make bad code.

Let's start off by asking ourselves how exactly do we write faster code? Is there some sort of secret key words? Special methods or functions? Or an advanced framework? Actually no. There are no special functions or methods into making our code run faster. It's actually a bit more simpler than that. We can start off with unused variables and move forward from there.

Unused Variables

I am pretty sure we have all seen the most common error in our console when working with JS.

variable is defined but never used

This is a very common mistake that a lot of beginners tend to just ignore because the variable sometimes wont have any value. So commonly we'll assume it has no affect to the code if it's not breaking it. But unused variables will cause performance issues since it is just taking up space in our browser. To put into simple terms, don't create variables if you don't plan on using them at all.

If you were to host a pizza party and invited 4 friends and each friend would eat exactly 2 slices of pizza, and each pizza comes with 8 slices. Would you order only the amount you need or will you order more pizzas even after knowing that your friends will only eat 2 slices? I'm sure we wouldn't want to waste any food or money, so in coding terms why would you create a variable and not use it, it would just be a waste and take up space.

Loop activity

When working with loops in our code, the loop will make an iteration over and over until returned true or false. This can cause a lot of heavy work to the CPU especially if we are looping through a big data structure with many objects. To help us make our loop a bit more efficient we can help by putting our assignments or statements outside of the loop so we don't iterate through the properties each time when we only need to access them once.

For example, here inside our loop we are accessing the arr.length every single time the loop iterates over and over, which can cause the code to perform slow over time, especially if we are working with a big database and need to find specific data.

var i;
for (i = 0; i < arr.length; i++) {}
Enter fullscreen mode Exit fullscreen mode

To help us implement a better for loop we can setup our variables outside of our for loop function so we can already have access to our array length instead iterating every-time and accessing through the loop. For example, we can assign our i and arr.length outside our loop and pass it in to make the loop run faster.

var i;
var l = arr.length;
for (i = 0; i < l; i++) {}
Enter fullscreen mode Exit fullscreen mode

Accessing the length outside the loop can sometimes make it easier to read for the developer, but also just like that you have implemented a faster loop iterator.

Javascript Loading

A lot of new developers don't really know where to place their script tags in the html file when first starting off. It is highly recommended that you put your javascript script file tags at the bottom of the html page so the browser is allowed to load up before loading in the functionality. This actually does make a huge difference in loading time for browsers. If the script tag is at the start of the HTML file, the browser will first download the script code before even loading anything else from the browser, rendering activity could even be blocked. You can also add your script to the browser after the page has loaded.

<script>
window.onload = function() {
  var element = document.createElement("script");
  element.src = "javaScriptCode.js";
  document.body.appendChild(element);
};
</script>
Enter fullscreen mode Exit fullscreen mode

Decrease DOM Access

Selecting or in other words Accessing the HTML DOM is very slow. We want to keep the number of elements we are selecting small, this will help with loading, speed, and will benefit smaller devices too. If we ever need to access a DOM element more than once, we can simply store it inside a local variable and access it only once.

var elm;
elm = document.getElementById("demo");
elm.innerHTML = "Hello";
Enter fullscreen mode Exit fullscreen mode

It might not seem like a lot but honestly these small mistakes can make a big difference when working with complex applications with tons of lines of code.

Conclusion

I hope by the end of this article you managed to learn how to create and understood what is going on in every line of code. It is very important to understand how your code fully works, not only does it help you become a better developer but can also help you use the tools you are working with more efficient.

These articles are mostly intended for personal use on becoming a better programmer, writer, and grow my programming skills. Feel free to drop any feedback or corrections that you believe that should be made to help me and others. Thank you for your time for sticking this far!

Discussion (18)

Collapse
hadaward profile image
Hadaward

There is another way to do the for loop:

for(var i=0, k=arr.length; i < k; i++) {}

The first division to define "i" is always called once and you can define as many variables as you like, this is even better because instead of creating a global variable you can use "let" and make local variables (it has better performance and keeps the code organized)

Collapse
metalmikester profile image
Michel Renaud

The examples in the article should use let instead of var anyway. Nice one with the "k" in your example.

Collapse
cleveroscar profile image
Oscar Pacheco Ortiz Author

You’re are correct, I still need to revise it and edit it! I really appreciate the feedback!

I know “let” is the new way to declare variables and “var” was pretty much the old school way.

Thread Thread
metalmikester profile image
Michel Renaud

It's not so much "new" vs. "old" school as they are not quite the same. "var" is basically available everywhere whereas "let" is limited to a scope.

Collapse
amansaxena001 profile image
Amansaxena001

Block scope is best either with let or IIFE

Collapse
lexlohr profile image
Alex Lohr

Accessing the length outside the loop can sometimes make it easier to read for the developer, but also just like that you have implemented a faster loop iterator.

Loops are already heavily optimized in most JS interpreters. Unless the length could change inside the loop, the length will be cached by the engine.

If you don't need to break or return from inside the loop, consider using array methods like forEach, reduce or map, which too are already optimized and can improve readability in some cases.

Collapse
lexlohr profile image
Alex Lohr

That being said, never forget the golden rule of performance: avoid premature optimization. And also the corollary: performance is more often an issue than you think.

Developers usually have strong PCs, unlike most of our user base, so negligible bottle necks for us may be the reason for them to dislike our product for being slow or draining their device's battery.

Collapse
valeriavg profile image
Valeria

Optimization needs to be measurable. You wont notice memory leaks by looking at the code. Instead, you should use profiler, lighthouse and other utilities at hand to find and mitigate performance problems. Unused variables are bad for readability but they hardly have any effect on the performance

Collapse
jamesthomson profile image
James Thomson

Exactly. Unless the unused variables are being constantly re-declared there should be no performance implications. The GC will clear it up from memory pretty quickly.... not that I'm condoning leaving unused variables in your codebase, but I think this is a moot point in terms of performance.

Collapse
cleveroscar profile image
Oscar Pacheco Ortiz Author

You’re right! I appreciate the feedback! I’ll make sure to add some of your info into the details.

I appreciate the feed back!

Collapse
val_baca profile image
Valentin Baca

It's been a while, but I actually ran the numbers on micro-optimizing the array-for-loop. Granted, this was pre-ES6 and the jsperf site is now gone, but I found that this was the fastest loop:

for (var i = 0, len = myArray.length; i < len; ++i) {
  // blah blah
}
Enter fullscreen mode Exit fullscreen mode

stackoverflow.com/questions/534942...

Collapse
khajin1 profile image
evalPenny

Accessing the length outside the loop will not just make it easier to read for the developer

Not me,
I've been using for (var i = 0; i < array.length; i++){}
too much that this is easier to read for me.

Collapse
rubinelezi profile image
Rubin Elezi
  • "Decrease DOM Access" That is very true, I have written a article about accessing the DOM as less as possible. A example can be when you are adding multiple elements to the DOM, with data maybe coming from an API. You should not attach them one by one, this is a huge performance killer on low end devices.

For more you can read: dev.to/rubinelezi/stop-touching-th...

Collapse
mwrpwr profile image
Joseph Maurer

You should do another post about ways to profile and speed up JavaScript! Good post!

Collapse
emil profile image
Emil • Edited

I think Array.length is very cheap since the size is not determined on each access

Collapse
cleveroscar profile image
Oscar Pacheco Ortiz Author

Woah! Thank you guys so much for all the feedback and support! I promise to fix my mistakes and reword things to help myself and those understand better.