My accountGet started

How to better optimize JavaScript code?

Few tips for a better optimization of JavaScript code. Decrease usage of CPU and memory consuption.

How to better optimize JavaScript code?

I decide to write up some tips for better optimization of JavaScript code. You can use these advices on client-side as well as server-side in Node.js.

1. Array optimization

Repetition is the mother of wisdom and a lot of programmers forget about caching length of the array in loops. This optimization can decrease CPU consuption.

2. Objects caching

I didn't see any similar optimization anywhere and I dare say that this optimization can increase performance and decrease CPU + RAM consuption. In the below example usage in Total.js (Node.js) controller:

A similar approach can be applied to Arrays.

3. Assignment of values is faster than creating new objects

This tip follows optimization tip #2. A value assignment is a lot faster than creating a new objects with subsequent assignment. Similar optimization can be used in Express.js or any other Node.js framework.

SUCCESS() method in Total.js framework uses the same optimization.

4. Do you use "delete" before "JSON.stringify()"?

If yes then I have a good optimization tip, which can increase performance a lot. The keyword delete is helpful, but too slow. Assigning undefined to the property will have the same effect as using delete.

5. Date caching also helps

There are cases when there's no need for an accurate time and +/- 1 minute is sufficient. In some cases is not needed an exact time, but it's sufficient +/- 1 minute of difference. I solve this cache via property F.datetime in Total.js framework. This property is refreshed each 1 minut about a new current datetime. So if you don't need exact time on the seconds then you can use my next tip for increasing of perfomance:

Real test:

6. "string.indexOf()" and "string.lastIndexOf()" vs regular expression

Methods string.indexOf() and string.lastIndexOf() are faster than regular expression and I recommend to use them for a simple search operations. Also it's helpful to know a differences between indexOf() and lastIndexOf() because here you can increase the performance, just think where is the most often search phrase.

7. Less code in the functions = better performance

Really nice post: I want to note that this optimization is for V8 only. Our product SuperAdmin increases the max-inlined-source-size limit automatically for all Total.js applications.

8. "" vs "function.apply" is faster than function.apply() but both calls are much slower then calls without change of the context.