How to better optimize JavaScript code?

Mon Oct 24 2016 07:13:08 GMT+0200 (Central European Summer Time), Peter Širka

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.

// BAD
var arr = [...];
for (var i = 0; i < arr.length; i++) {

}

// BETTER
var arr = [...];
for (var i = 0, length = arr.length; i < length; i++) {

}

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:

// SLOW
function some_action_with_json_response() {
    this.json({ success: true });
}

// MUCH FASTER
const response = { success: true };

function some_action_with_json_response() {
    this.json(response);
}

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.


// SLOW
function some_action_with_json_response() {
    this.json({ success: this.query.success === '1' });
}

// MUCH FASTER
const response = { success: true };

function some_action_with_json_response() {
    response.success = this.query.success === '1';
    this.json(response);
}

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.

// SLOW
var obj = { name: 'Peter', age: 30 };
delete obj.name;
console.log(JSON.stringify(obj)); // { age: 30 }

// MUCH FASTER
var obj = { name: 'Peter', age: 30 };
obj.name = undefined;
console.log(JSON.stringify(obj)); //{ age: 30 }

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:

// The variable below will have always current datetime in +/- 30 seconds interval.
var datetime = new Date();
setInterval(function() {
    datetime = new Date();
}, 30000);

Real test:

require('total.js')

console.time('With cached Date');
var dt_c = null;
for(var i = 0; i < 1000000; i++) {
    dt_c = F.datetime;
}
console.timeEnd('With cached Date'); // about 5ms

console.time('Without cached Date');
var dt_wc;
for(var i = 0; i < 1000000; i++) {
    dt_wc = new Date();
}
console.timeEnd('Without cached Date'); // about 250ms

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: https://top.fse.guru/nodejs-a-quick-optimization-advice-7353b820c92e. 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. "function.call" vs "function.apply"

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


Tags

Follow us

Latest blogs
Total.js Wiki v2
Fri Jan 04 2019 22:15:01 GMT+0100 (Central European Standard Time)
Total Year 2018
Thu Jan 03 2019 21:14:00 GMT+0100 (Central European Standard Time)
Total.js Code Editor v1
Fri Dec 07 2018 22:55:13 GMT+0100 (Central European Standard Time)
New release: Total.js v3.1
Fri Dec 07 2018 11:41:40 GMT+0100 (Central European Standard Time)
New CDN for Flow + Dashboard + Flowboard
Sun Nov 04 2018 09:05:03 GMT+0100 (Central European Standard Time)

Latest comments
Nice tip
Mauro Junior
Thu Sep 20 2018 21:41:02 GMT+0200 (Central European Summer Time)
Not only for Total.js. You can communicate with different websocket servers.
Peter Širka
Mon Apr 23 2018 20:08:20 GMT+0200 (Central European Summer Time)
Marko: you need to create a buffer with this codepage and write byte-to-byte string. I recommend ...
Peter Širka
Mon Apr 23 2018 20:06:21 GMT+0200 (Central European Summer Time)
Is WEBSOCKETCLIENT only for internal ws connections between totaljs apps?
Stelios Stephanua
Fri Mar 16 2018 06:04:22 GMT+0100 (Central European Standard Time)
Total.js is amazing! ;)
Leonardo Hessel
Tue Dec 19 2017 19:51:15 GMT+0100 (Central European Standard Time)

Pixabay


Read more

Total.js Wiki v2

Products: I have released a new version of Total.js Wiki. New version brings new improvements.

Fri Jan 04 2019 22:15:01 GMT+0100 (Central European Standard Time)
Total Year 2018

Business: Last year was perfect for Total.js platform. Total.js platform grows up and it has great results.

Thu Jan 03 2019 21:14:00 GMT+0100 (Central European Standard Time)
Total.js Code Editor v1

Products: Try our real-time collaboration tool for Total Developers. Code Editor offers great features for development.

Fri Dec 07 2018 22:55:13 GMT+0100 (Central European Standard Time)
New release: Total.js v3.1

News: I have released a new version of Total.js with bug fixes and with small improvements.

Fri Dec 07 2018 11:41:40 GMT+0100 (Central European Standard Time)
New CDN for Flow + Dashboard + Flowboard

News: I have changed CDN for Flow + Dashboard + Flowboard components to KeyCDN.

Sun Nov 04 2018 09:05:03 GMT+0100 (Central European Standard Time)
OpenPlatform v3

News: I have published a new version of OpenPlatform. New, better, faster, more secure and more simpler.

Mon Oct 15 2018 10:11:07 GMT+0200 (Central European Summer Time)