This article is a combined effort of Innofied Javascript developers Puja Deora and Subhajit Ghosh)

We have been working on a project for past 8 months (ongoing). Over the course of this project, we have learnt that small tweaks to general coding practices goes a long way in improving the overall performance of the code.

In this article, we will discuss some of these common JavaScript practices and tricks to code optimization that improve the overall efficiency and performance of our code. Most of the techniques described below are fairly intuitive once we grasp the underlying problem or overhead.

1. Chain of Command

JQuery Chaining is a very powerful feature of jQuery that connects multiple functions and events on a particular selector. The following example shows how chaining makes our code shorter and faster.
Code 1

 
 
 
 
 
 

JavaScript

 
1
2
3
$('.element').removeClass('old');
$('.element').addClass('new');
$('.element').show();

Code 2

 
 
 
 
 
 

JavaScript

 
1
2
$('.element').removeClass('old')
.addClass('new').show();

The problem with code 1 is that for every statement, jQuery has to search the entire DOM and find the element and after that execute the attached function on it. But when chaining is used, jQuery has to find the element only once and it will execute all the attached functions one by one. So, Code 2 is optimized.

2. Event Management

Using jQuery, we can attach events to an element in the following two ways:

Code 1

 
 
 
 
 
 

JavaScript

 
1
$(‘selector’).click(function() {});

Code 2

 
 
 
 
 
 

JavaScript

 
1
$('parent-selector').on('click', 'selector', function callback(){});

The second method is better as it allows us to bind events to dynamic HTML elements.

3. Out of Scope

Every time we define a new function and create a new closure, javascript adds a level to its scope chain. When the browser resolves properties, each level of the scope chain must be checked. In other words, JavaScript looks at the first item in the scope chain, and if it doesn’t find the variable, it bubbles up the chain until it hits the global object.

That’s why global scopes are slow. They are worst-case scenarios for object lookups.

Example Code

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
8
9
10
var outer = 'outer';
var sampleFunction = function() {
    var inner = 'inner';
    return function() {
        var efficient = 'efficient';
        outer;
        inner;
        efficient;
    };
};

Here when the function is invoked referencing outer is slower than referencing inner, which is slower than referencing efficient.

4. Power of Native functions and constructs

Its good to be aware of native constructs provided by ECMAScript as it saves us from having to write our own algorithms. Some commonly used constructs are-

  • Math.floor() and Math.round() for arithmetic operations
  • (new Date()).getTime() for timestamps
  • String.prototype.match() and String.prototype.replace() for regexes
  • parseInt(n, radix) for changing numeral systems
  • === instead of == for faster type-based comparison
  • instanceof for checking type up the hierarchy
  • & and | for bitwise comparisons.
  • && and || operators instead of simple if-else statements.

5. Use ‘this’ the right way

In case of using asynchronous code blocks, a common practice is to use global or closure variables to refer to object properties outside the scope of the asynchronous block. For example:

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
var Test = function() {
    var me = this;
    this.x = 5;
    return function() {
console.log(me.x);
    };
};

As discussed in point number 3 above, this takes longer time as the closure variables (in this example, me) are held at a higher level of the scope chain. We can improve this by binding the correct scope to our asynchronous function when we call them. For example,

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
var Test = function(callback) {
    this.x=5
    callback.call(this);
};
Test(function(){
    console.log(this.x)
}); //output is 5

6. Define class methods with prototype

We can define a method of a class in the following two ways:

Method 1

 
 
 
 
 
 

JavaScript

 
1
2
3
4
MyClass = function() {
    var privateVariable;
    this.privilegedMethod = function() {};
};

Method 2

 
 
 
 
 
 

JavaScript

 
1
MyClass.prototype.publicMethod = function() {};

When we define a class method using prototype (Method 2), only one copy of the function is created which is shared by all object instances of the class. The context within the function will refer to the instance which calls it. Hence, it is a more efficient way of defining methods than using ‘this’.

7. Avoid referencing Object properties

Reading an object property takes longer than reading a variable. It would do us good to remember this when we are referring to some object property frequently. We could improve our code’s performance by storing this property in a temporary variable.

Method 1

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
var stringFill1 = function(string, count) {
    var result = '';
    while (result.length < count) {
        result += string;
    }
    return result;
}; // Execution time for this function is 47.297 microseconds

Method 2(Optimized)

 
 
1
2
3
4
5
6
7
var stringFill1 = function(string, count) {
    var result = '';
    while (count-- > 0) {
        result += string;
    }
    return result;
};// Execution time for this function is 27.68 microseconds

8. Batch style updates

In case we need to make several style updates for a particular DOM element, it is better to apply those changes at once instead of applying them one by one. This prevents the UI from being rendered repeatedly. In the following example, Method 2 is better than Method 1.

Method 1

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
// This will incur 5 screen refreshes
jQuery('.element')
    .width(600)
    .height(400)
    .css('position': 'absolute')
    .css('top', '200px')
    .css('left', '200px');

Method 2

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
8
// Let jQuery handle the batching
jQuery('.element').css({
     width: '600px',
     height: '400px',
     position: 'absolute',
     top: '200px',
     left: '200px'
);

When working with similar cases as described in the above example, there is another way that’s far more efficient than using jQuery’s CSS method. We could add a new class to the DOM element and write the style changes against that class in our CSS file.

Efficient Method

 
 
 
 
 
 

JavaScript

 
1
jQuery('.element').addClass('prefferedClass');

9. Build DOM ‘off-line’

Every time we add a DOM element to the UI, it refreshes the entire screen. We can improve that by building DOM ‘off-line’ and adding it to the UI at once.

Method 1

 
 
 
 
 
 

JavaScript

 
1
2
3
4
var list = $('<ul></ul>');
$(list).append('<li>Sample1</li>');
$(list).append('<li>Sample2</li>');
$(list).append('<li>Sample3</li>');

Method 2(Optimized)

 
 
1
2
3
4
5
6
var list = $('<ul></ul>'),
    htmlBuffer=[" <li>Sample1</li>",
"<li>Sample2</li>",
"<li>Sample3</li>"].join("");
 
$(list).append(htmlBuffer);

10. Many-to-one

After we have completed developing our .js files, we can pass them through a javascript minimizer tool (such as JsMin) which removes the unnecessary code blocks (read comments and white spaces). This way, we just have to add one minified script file to our HTML. Its better because a request to fetch one comparatively larger file executes faster than the request to fetch multiple smaller files.

11. Dependency Manager

The idea is to load modules to the browser as and when they are required. When a user requests for a page, the first thing they notice is the HTML content. The functionality is required only after they get familiarised with the layout. We can achieve this by working with dependency managers likeRequireJS or Browserify.

12. Better String concatenation

String concatenation causes major problems with Internet Explorer 6 and 7 garbage collection performance.

Method 1

 
 
 
 
 
 

JavaScript

 
1
var longString = "This is a long String" + "So the question is how to concatenate a string" + "in a better way";

Method 2

 
 
 
 
 
 

JavaScript

 
1
var longString = ["This is a long String" , "So the question is how to concatenate a string" , "in a better way"].join(" ");

When we concatenate some substrings to create a larger string, all intermediate results are stored in temporary variables. Therefore the second method is optimized as it requires lesser memory for execution.

13. Indexing power of Javascript Objects

Lengthy if-else blocks can be reduced to a single line of code. All we need to do is create a Javascript object to map each condition to a function name. It works in a manner similar to HashMap data structures. The following example illustrates this technique.

Method 1

 
 
1
2
3
4
5
6
7
if(action === 'add'){
  onAdd();
}else if(action === 'edit'){
  onEdit();
} else if(action === 'delete') {
  delete();
}

Method 2(Optimized)

 
 
1
2
3
4
5
6
var actions = {
  'edit' : 'doEdit',
  'delete': 'delete',
  'add': 'onAdd'
};
actions[action]();

14. Primitive vs Reference variable types

Primitive variables and reference variables behave differently when we pass them as parameters for a function call. A copy of primitive variables is created in the function whereas only a light-weight reference is passed to the new function, in case of reference type variables. So whenever we need to pass a few parameters to a function, it is better to create a config object and pass a reference to that instead.

15. Use defineProperty/defineProperties

defineProperty gives us more control over the behaviour of object properties that we define. We get options to- prevent further modification or deletion after an object property has been defined, control whether the property shows up during enumeration or not and so forth.

Let’s consider the example of data structure Stack. We define the push method for Stack as follows:

 
 
 
 
 
 

JavaScript

 
1
2
function Stack(){};
Stack.prototype.push = function(x){/* */}

Since we are dealing with Stack, ‘push’ will be an integral method for any implementation. We would be referring it repeatedly and wouldn’t want anything to modify, overwrite or delete our definition. This can be controlled by defining it as follows:

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
8
9
function Stack() {
};
Object.defineProperties(Stack.prototype, {
    push: {
        writable: false,
        configurable: true,
        value: function (x) { /* ... */ }
    }
});

Another advantage of working with defineProperty is that we can use the getter/setter methods to get or set the value for an object property.

 
 
 
 
 
 

JavaScript

 
1
2
3
4
5
6
7
8
9
10
11
12
var square ={
    width: 20,
    height: 30
};
 
Object.defineProperty(square, 'area', {
    get: function(){
        return this.width*this.height;
    }
});
 
console.log(square.area);

Here the get method is called implicitly when we refer to square.area. Read here for more information on defineProperty.

These are some of the many best practices that we have found effective. We hope you find these helpful. Do comment and share optimization techniques from your experience. Happy coding.

Code optimization and organization in Javascript / jQuery的更多相关文章

  1. 在线运行Javascript,Jquery,HTML,CSS代码

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" http://www.w3.org/TR/xht ...

  2. javascript --- jQuery --- Deferred对象

    javascript --- jQuery --- Deferred对象 javascript的函数式编程是多么引人入胜,jQuery使代码尽可能的精简,intelligent! defer - 必应 ...

  3. 使用Javascript/jQuery将javascript对象转换为json格式数据 - 海涛的CSDN博客 - 博客频道 - CSDN.NET

    body{ font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI& ...

  4. Handlebars的基本用法 Handlebars.js使用介绍 http://handlebarsjs.com/ Handlebars.js 模板引擎 javascript/jquery模板引擎——Handlebars初体验 handlebars.js 入门(1) 作为一名前端的你,必须掌握的模板引擎:Handlebars 前端数据模板handlebars与jquery整

    Handlebars的基本用法 使用Handlebars,你可以轻松创建语义化模板,Mustache模板和Handlebars是兼容的,所以你可以将Mustache导入Handlebars以使用 Ha ...

  5. JavaScript jQuery 中定义数组与操作及jquery数组操作

    首先给大家介绍javascript jquery中定义数组与操作的相关知识,具体内容如下所示: 1.认识数组 数组就是某类数据的集合,数据类型可以是整型.字符串.甚至是对象Javascript不支持多 ...

  6. VS Code - Debugger for Chrome调试JavaScript的两种方式

    VS Code - Debugger for Chrome调试JavaScript的两种方式 最近由于出差的缘故,博客写的不是很多,一直想写一篇VS Code - Debugger for Chrom ...

  7. javascript/jquery读取和修改HTTP headers

    javascript/jquery读取和修改HTTP headers jquery修改HTTP headers jQuery Ajax可以通过headers或beforeSend修改request的H ...

  8. 大量Javascript/JQuery学习教程电子书合集

    [推荐分享]大量Javascript/JQuery学习教程电子书合集,送给有需要的人   不收藏是你的错^_^. 经证实,均可免费下载. 资源名称 资源大小   15天学会jQuery(完整版).pd ...

  9. [推荐分享]大量Javascript/JQuery学习教程电子书合集,送给有需要的人

    不收藏是你的错^_^. 经证实,均可免费下载. 资源名称 资源大小   15天学会jQuery(完整版).pdf 274.79 KB   21天学通JavaScript(第2版)-顾宁燕扫描版.pdf ...

随机推荐

  1. IE中div被视频遮住的解决方法

    使用embed来内嵌视频,因为视频是windows media player,上面想用div浮动一些内容,之前尝试了一些方法,比如 1. 通过设定不同组件的z-index值 2. 通过设定 wmode ...

  2. The .NET weak event pattern in C#

    Introduction As you may know event handlers are a common source of memory leaks caused by the persis ...

  3. C#中泛型容器Stack<T>的用法,以及借此实现”撤销/重做”功能

    .Net为我们提供了众多的泛型集合.比如,Stack<T>先进后出,Queue<T>先进先出,List<T>集合元素可排序,支持索引,LinkedList<T ...

  4. C#编程(三十三)----------Array类

    Array类 创建数组 Array intArray1 = Array.CreateInstance(typeof(int), 5); for (int i = 0; i < 5; i++) { ...

  5. 斯巴达克斯诅咒者之战第三季/全集Spartacus迅雷下载

    本季Spartacus 3第三季(2013)看点:<斯巴达克斯>系列是美国Starz电视网历史上的首部原创作品,凭借其重口味的流血镜头.香艳的画面.血腥的打斗场面和优良的制作一经推出就瞬间 ...

  6. Unable to execute dex: Multiple dex files define 的解决方法

    我们在引入library时可能会出现这个错误 比如: [2013-11-05 14:22:15 - Dex Loader] Unable to execute dex: Multiple dex fi ...

  7. 访问修饰符(C# 编程指南)

    所有类型和类型成员都具有可访问性级别,该级别可以控制是否可以从你的程序集或其他程序集中的其他代码中使用它们. 可以使用以下访问修饰符在进行声明时指定类型或成员的可访问性: public同一程序集中的任 ...

  8. Apache Jmeter 教程

    Jmeter是一款优秀的开源测试工具, 是每个资深测试工程师,必须掌握的测试工具,熟练使用Jmeter能大大提高工作效率. 熟练使用Jmeter后, 能用Jmeter搞定的事情,你就不会使用LoadR ...

  9. 基于DPI(深度报文解析)的应用识别

    一.概述 1.DPI(Deep packet inspection,深度报文解析) 所谓“深度”是和普通的报文分析层次相比较而言的,“普通报文检测”仅分析IP包4 层以下的内容,包括源地址.目的地址. ...

  10. asp.net网站发布

    1.iis里面新建一个网站,目录可以新建(例如:F:\dotNetWeb),还可以创建子文件夹如:F:\dotNetWeb\my,网站路径是可以自己设置的,也可以使用IIS默认的网站. 2.vs201 ...