Javascript performance tips

Today, hardware upgrades are usually a cheaper alternative. So, it is not worth to focus on performance improving. But spending time on improving performance could save more than 50 new upgrades with simple code improvements that account for a 50x+ performance increase.

I’ve worked on some project and theme development. The performance is important with each project. I collected some tips below to help other have more great product.

Loops

When simple iterations are required, in other words repeating an action n times, we will often use a while instead of a for a loop.

and

Do you think which type is faster? The number #1?

No, it is not. The number #2 with while is faster than #1 one.

Let check chart below:

Source: ModusCreate

So, I recommend you to use the while loop.

Accessing Object Properties

Deeper in a property nested, more time will be required to perform the property lookup. Yes, there is a performance penalty.

Ex:

Let’s check the line into the for loop. To each to Viewport item, firstly browser have to access Lumise object, then find the view reference and access it, then find stages reference and access, after that find the Viewport reference and find an item with index i. There are too many references each time of loop. It let browser getting RAM much for that work. So what is solution?

If there are multiple references to a particular deeply nested object, then you create a temporary local variable that points to the common object and then references from that within the local function.

Ex:

So easy to solve it.

String Concatenation

Suppose you have a couple lines HTML for readable and organization benefits in addition to business logic purposes. In the normal way, we will use the common concatenation:

That is the great performance, but it is hard to read them.  So, we can arrange them into elements of an array as:

We created an array of strings and used Array.prototype.join to combine them into one. Of course, it’s much prettier than combining with a + sign, and the code is more readable, too. But the [].join() is slower.

What is the solution? Simply, we use the String.prototype.concat method to combine them, your code still readable but faster.

This solution is helpful in case you have a couple of variables with unknown types and you want to concatenate them in a string.

 

Conclusion

On next articles, I will tell you more tips and tricks to improve your web application performance.

Do you have your own findings on the topics presented? Do you have additional suggestions to show? Please share your thoughts with the rest of us.