101 Javascript performance improvement techniques




Variables and Declarations

1. Variables much better than array and objects

Javascript is untyped language but the performance improvement starts from declaring variables and accessing them. Variables and literal values faster than object properties and array items look ups.
Declaring variables and accessing them

var user_email = 'xxx@xx.com';

console.log(user_email); //xxx@xx.com

Declaring objects with properties

var user = {email: 'xxx@xx.com'};

console.log(user.email); //xxx@xx.com

2. let is faster than var in function scope

let is block scoped and var is block scoped. let clears the memory when it is not needed, var exists all over function scope, so let always faster than var when there are different blocks. let solves the closures problem too.
Declaring variables with var and let

for(var i=0;i<length;i++){...}
for(let i=0;i<length;i++){...}
            
jsperf

3. Make sure that there is no native method for the same job

The same job you can do using native method and in your way of implmentation. if you are going to implement the functionality, take time to find native method can do the work. Native methods can give you better performance.
Sample for using native methods

var arr = [];
arr.push(1);
arr.pop();
            

4. Combine the variable declarations

Declaring the variables can also be optimizable. All the declarations should be in one statements, this handle the memory allocation for all at one time.

var foo,
    blah,
    flag;
            

5. Assign value in creation time, updations costs more.

if you seperate creations and value assignment of variables that would be a bad design. Assign the default values at the time of creations.

var foo = "str",
    blah = 10,
    flag = false;
        

6. Literals executes faster than Objects.

Literal notation executes faster than object notation when declaring variables with datatype constructors.
Declaring a variable in literal notation

            var str = 'string';
            var obj = {a:1,b:2};
            
Declaring variables using datatype constructors

            var str = new String();
            var arr = new Array();
            

7. For toggling purpose use 0/1 instead of Boolean type.

Using 0/1 helps to increase the performance, the value numeric values always better than boolean datatype.

            var flag = 0;
            
            function toggleFlag(val){
                if(val){
                    val = 0;
                }else{
                    val = 1;
                }
                return val;
            }
            

8. Do not use concat for string concatenation, use '+'

For concatenation use "+" and the native method concat doesn't perform well, when considering the performance.

            var str = "this";
            str += "is";
            str += "awesome";
            

9. parseInt can be replaced with ~~(1,'12.5')

parseInt job can be done by the statement ~~(1,numericString) with better optimization.

                var numberStr = '12.5';
                parseInt(numberStr); // 12.5
                ~~(1,numberStr); //12.5
                

10. Compound assignment of let or const give bad results

This is the issue with compiler, the function containing let or const are not optimizable.

Arrays

11. Avoid multi-dimensional arrays

Array items lookup bit costly, in case of multi-dimentional arrays that delivers not good results. Multi-dimentional array look up goes through each dimension every item comparison.

            var maArr = [[1,2,3],[4,5,6],['a','b','c']];
            mArr[2][0] // returns 'a' 
            

12. Use array native methods for doing operations

As I discussed in early steps, I always recommend a native method in case of array manipulations, as most developers not aware of all methods. In case of array manipulations look ups and index handling are heavy operations, so better to go with native methods to perform the operations as much as possible.

13. For simple array findings use indexOf.

oh, yah! indexOf., you are about to find the existence of an item in simple array, user it. Finding the existence by looping through all the items in the array is bad for simple arrays.

            var simpleArr = [1,2,3,4];
            function find(arr, item){
                return arr.indexOf(item) !== -1; 
            }
            find(simpleArr,3); // returns true;
            

14. Use binary search for finding elements in array

Why binary search? in case of complex arrays binary search gives the difference compared to other techniques.

15. Arrays are faster than objects

Array look ups and index manipulations are faster than object properties manipulations, array manipulations deals with index but object properties needs lot of comparisons.

            var arr = [1,2,'c'];
            var obj = {foo:1,blah:2};
            arr[0];
            obj[blah];
            
jsPerf

16. Arrays with holes in it gives much impact on objective

Array should be well defined and need care in manipulations. Holes with in a array has the impact on performance and the manipulations needs high computations.

            var arr = [1,3];
            arr[4] = 'a';
            //wow you did it, you created an array with holes.
            

17. Array join faster than string concatenation

yes, it's true. Array join performs well in case of concatenating strings, thats proven by the performance benchmarks. its seems to be long way but it makes us to reach objective.

            var str1 = 'am';
            var str2 = 'awesome';
            var arr = [];
            arr.push(str1);
            arr.push(str2);
            arr.join(); // "am awesome"
            str1 + 'I' + str2; // "am I awesome"
            
            
jsPerf

18. Use splice(0,length) to clear the array

How do you clear an array, are you assigning new empty array to it, that's not good way. Array method splice can work better in this case.

            var arr = [1,2,3];
            arr.splice(0,arr.length); // arr => []
            
            
jsPerf

19. Typed Arrays are faster than native arrays

Typed arrays performs lot better than normal javascript array becuase typed array views are like single type arrays.

             var s_tyarrayUint8 = new Uint8Array(256 * 256 * 4);
            var s_tyarrayUint32 = new Uint32Array(256 * 256);
            
jsPerf MDN

20. Array.forEach wont give you much better results

The array native looping method forEach needs functions executions for each item in the array, so its always a bad choice for iterating through all the items in array. Use for loop as an alternative for it.
Iterating aray items with forEach

            var arr = [1,2,3,4];
            arr.forEach(function(){// doing something});
            
Iterating using for

            var arr = [1,2,3,4];
            
            for(var i=0;i<arr.length;i++){
                //some code
            }
            

Objects

21. >Construct objects instead of array when u need to do more find operations

when you need more find operations for set of items, constructing object will help you and performs well.

            var users = {axorg :{id:'axorg', name:'George'},
            byorg:{id:'byorg', name:'John'}};
            users['byorg']; // easiest way to find user object using id
            

22. Use Object.keys() to get list of keys in object

To get list of keys use the native method Object.keys() because looping through all object properties costs more computations.

            var obj = {a:1,b:2};
            Object.keys(obj); // return ['a','b']
            

23. Use property check instead of hasOwnProperty

Though hasOwnProperty its own significance, doing property check give you advantage over hasOwnProperty.

            var task = [{name:"do1",selected:true},{name:"do2"}];
            var selectedTasks = 0;
            for(var i=0;i<task.length;i++){
                if(task[i].selected){
                    selectedTasks++;
                }
            }
            

24. Avoid Object.create() instead use new

Object.create() have many advantages over new still its not good to go with it, performance petrices revealed that.

             function myClass(){
                //class definition
             }
             var klass = new myClass;
            
jsPerf

25. Make it undefined instead of using delete to clear the properties from object

delete leads to object manipulation, but making a property undefined wont cause for object recustruction.

            var obj = {prop1:1,prop2:2};
            delete obj.prop1; // don't do it.
            obj.prop1 = undefined; // its better
            

26. Object.defineProperty() costs more than direct property assignment

Object.defineProperty() it has so many features for controlling the property behaviour that makes the performance down, unless it is a public property don't define properties using Object.defineProperty()

            var obj = {};
            obj.prop1 = 1;
            obj.prop2 = 2;
            Object.defineProperty(obj,'prop3',{value:4});
            

Statements and Expressions

27. Do not use with statement.

A well known proverb "do not use with", we can consider as one of the dangarous things in javascript. By using it you won't get much benfit but you will be in danger in case of missing properties in passed object. It updates global variabels if there are no properties in passed object.
updating the object using with

            with (myObj) {
    foo = true;
    blah = true;
}
            
doing the same thing

            var objCopy = myObj;
            objCopy.foo = true;
            objCopy.blah = true;
            

28. Do not use eval

Here comes the evil of the javascript. eval opens a hole to support attackers. its executes the code slowly.

            eval("alert('hahahaha')"); //see the evil laugh
            

29. Clear the timers, once the your tasks are finished

clearInterval help you to clear the interval in javascript. what happens to the uncleared intervals, they runs forever.

            var interval, count = 0;
            interval = setInterval(function(){
            if(count == 1000) clearInterval(interval);
            count++;},100);
            

30. Avoid animations with JavaScript

Do not play with javascript variables, even though we have powerful engines making our main thread busy leads to unresponsive dialog or huge amount of memory occupation.

31. Do not hit userAgent maximum space allocated for localStorage/sessionStorage

If the localStorage space reaching to the limit set by user agent and you are still trying to make operations on localStorage it always goes slow.
//pushing records to localStorage

            for(var i;i<10000 code="" generaterecords="" guid="" i="" localstorage.setitem="">

32. Limit number of requests to localStorage

Number requests to persistent storage space proportionally equals to performance impact.

33. Comments need space

Though comments dont have much impact on performance but comments increases the files size that leads to increase load time, so its better to remove comments in production.

34. Make use of threading in Javascript

Do the heavy operations in separate thread, Web Workers help you to implement this in Javascript. WebWorkers creates seperate threads in javascript.

            var myThread = new WebWorker(url);
            myThread.onmessage = function(){
                //receives msgs 
            };
            myThread.postMessage(msg);
            

35. Use minimum number of web workers

There is a limit to number of webworker instances for same origin.

            

36. Do not Send and Receive large amounts of data.

Sending or Recieving data objects creates copies of the objects, in case of large amounts of data passing threads needs more momery allocations that would slowdown execution.

            

37. Websockets can give boost to your application

Implementing websockets let you get rid of http overhead, this technique can make you to build responsive realtime web applicatios.

            

38. Use requestAnimationFrame for better performance in using intervals.

If you are going to large operations on client-side like animations, iterating in frequent intervals, requestAnimationFrame helps to give smooth presentation without blocking the thread.

reqAF = window.requestAnimationFrame;

  var degrees = 0;
  function updateSel(timestamp) {
    document.querySelector('#foo').style.webkitTransform = "rotate(" + degrees + "deg)";
    console.log('updated to degrees ' + degrees);
    degrees = degrees + 1;
    reqAF(updateSel);
  }
  reqAF(updateel);
            

39. Give the preference to native in case of base64 encoding or decoding atab and btoa.

The best native and performant way for encoding and decoding data to and from base64. atab will give you the actual data from base64 encoded data. btoa. gives you base64 encoded data of the passed data./p>

            var str = ""RK_Awesome";
            var bStr = btoa(str);//returns base64 data
            var aStr = atob(bStr);//returns actual data
            
jsPerf

Regular Expressions

40. test is faster than exec when using regular expressions

Usually we will go with test to verify the regExp but exec always performs better than text.

            var str = "hello world!";
var result = /^hello/.test(str);
console.log(result); // true
var result = /^hello/.exec(str);
console.log(result); //returns matches array

            
jsPerf

41. search is faster then match

Here we have two string methods takes regular expression and finds the in the content search and match, which can be comparable, but the search wins.

            var str = "hello world!";
            var re = /^hello/;
var result = str.search(re);
console.log(result); // index of first match or -1
var result = str.match(re);
console.log(result); //returns matches array or null
            
jsPerf

42. replace works well compared to split and join.

Another string method performs better than a well used technique. Prefer to use replace for replacing a string in other string.

            var str = "Hello world";  
            str.replace("Hello", "Google");// good to go
            str.split("Hello").join("Google");// bad practice
            
            
jsPerf

Control statements

43. Avoid else-if, use switch instead.

44. Use !! if you are checking non-Boolean values.

45. Strict comparison slower than value comparison.

46. if-else faster than ternary. jsperf

47. Do not exceed your switch cases more than 128.

48. typeof is much faster than instanceOf. jsperf

49. Give first preference to boolean conditions when you are checking multiple conditions.

50. Write fail proof code and avoid try/catch.

51. try/final also gives same impact like try/catch put them in a function and call them to use

Loops


52. Avoid for-in loops.

53. Avoid for-of loops.

54. Mix conditions with control variables when using loops.

55. Use decrements instead of increment if possible.

56. Use break and continue.

57. Long Running Scripts.

Functions


58. Use closures.

59. Apply closure instead of bind.

60. Use call or apply or bind when binding or calling the functions to avoid correct this.

61. Use call instead of apply.

62. Create instance instead of creating object.

63. Creating instance with new better than calling a function. jsperf

64. Return direct value not the reference.

65. Do not create anonymous functions.

66. Pass less arguments to the function.

67. passing objects, arrays, dates are better than strings, boolean values

68. Prototype methods significantly faster then class methods.

69. Function expression slower than function declaration. jsperf

70. Never return arguments array or reference of it. it causes for memory leak. copy the arguments to a new array and return if you want to return.

71. Don't try to manipulate arguments object or create a variable with arguments name.

72. Returning a value always faster than implementing callback.

73. Don't touch __proto__ in your function declaration.

74. get and set declarations makes the functions unoptimizable.

75. Functions have debugger statement never think about performance.

76. Avoid recursions.

77. Native promises faster than callbacks. jsperf

DOM


78. Do not use global object directly, use references to those objects when you are doing multiple operation using the same object.

79. Use arrays instead of HTML Collection objects.

80. Avoid DOM Manipulation.

81. Do not change styles directly, deal with classes instead.

82. ClassName give better results than ClassList. jsperf

83. Batch your DOM changes.

84. Less DOM gives you much better performance.

85. Separate the DOM creation and adding.

86. Prefer to load DOM on demand.

87. Load the scripts after DOM load.

88. Compare nodes not the attributes

89. Better to use document.querySelector instead of Element.querySelector.

90. Data attribute selectors are slower than CSS selectors.

91. Attributes faster than data-* attributes.

92. Be careful with these things, you may lead to browser favorite dialog. Too much DOM interaction.

Event handling


93. Be care full with event bindings.

94. Take extreme care on events fires in less times.

95. Turn off the events when you are done.

96. Lock the events with in the scope.

97. Mouse-up event instead of click event.

Transportation and Delivering


98. Load dependencies on demand.

99. Minify your code for production.

100. Follow AMD pattern for best practices.

101. Use Caching more.

102. Use CDNs to load scripts fast.

Share this

Related Posts

Latest
Previous
Next Post »