Javascript. 6 tips to improve the performance of the code you write

List of tips that are easy to implement on a day-to-day basis to help you write more optimized Javascript code

Compute only once

Many times we do not pay attention to the times that we force Javascript to reserve memory for the same object or to perform the same heavy calculation:

function calculateSomethingHeavy() {
...
}
function foo(bar) {
const result = calculateSomethingHeavy();
// do something with result and bar
}
foo(1);
foo(2);
function foo(bar) {
const object = { key: 'value'};
// do something with bar
}
foo(1);
function calculateSomethingHeavy() {
...
}
function fooCreator() {
const result = calculateSomethingHeavy();
return foo(bar) {
// do something with result and bar
}
}
const foo = fooCreator();foo(1);
foo(2);
const module = (function foo(bar) {
const object = { key: 'value'};
// do something with bar
return {
doSomething: function(bar) {
// do something with bar
}
}
})();
module.doSomething(1);

Use native methods

Many times we tend to write functions that do things that Javascript itself already has implemented in the form of native functions of the language.

function applyFunctionToArray(arr, fn) {
const newArray = [];
for (let i = 0; i < arr.length; i ++) {
const result = fn(arr[i]);
newArray.push(result);
}
return newArray;
}

Avoid “delete”

We can use the delete word to delete a key from an object. However, it has a counterpart: when we use it, the V8 engine begins to treat that object as if it were a “flat” object, eliminating a series of optimizations that it performs underneath.

const obj = { 'foo': 1, 'bar': 2, 'zeta': 3};
obj.foo = undefined;
const obj = { 'foo': 1, 'bar': 2, 'zeta': 3};
const {foo, ...objectWithoutFoo} = obj;

Split your code

When we create web applications, one of the most important things we have to pay attention to is getting the code to load as quickly as possible so that the user can see “something” as quickly as possible.

Not everything has to be flat objects

For some years now, Javascript has had a series of special objects that are optimized for certain types of tasks.

const arr = [1, 2, 1, 2, 3, 4];
const arrayWithoutDuplicates = [...new Set(arr)];

And to finish … take care of the libraries / packages you use

There is a series of libraries that are usually installed at the beginning of projects and that nevertheless tend to be quite “heavy”, which causes the final files of our application to reach a large size.

Final thoughts

As you can see, all these tips are very easy to implement in our applications and following the saying that “everything adds up” will help us to have much more optimized and faster applications.

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store