Category Archives: JavaScript

High Performance JavaScript

Because I change my job recently, I move from backend developer to front-end developer. I will write down some knowledge related to front-end step by step. But I still will use my free time to fulfill unfinished study on backend. It is not a new start, but a continue.

In fact, before I quit the previous job, my tasks already switched between front-end development and back-end such as involving in website development. It is not systematic study. This post will follow a book, named “High Performance JavaScript” to arrange related knowledge about JavaScript systematically.

Before we start to talk about the detailed knowledge, we need to realize why we want “High-Performance JavaScript”, not others, like “Programming in JavaScript”. The reason is that it is quite easy to write JavaScript code and make it running (I use two weeks to learn it). However, how to make it run as efficiently and quickly as possible is a serious question. So high performance becomes the main factor we need to consider when we write down codes. We should care about execution time, loading, interaction with the DOM, page life cycle and more. I will not copy book’s content but write down my understanding with my logic.

Let’s go.

Loading and Execution

JavaScript Position: put scripts at the bottom

When the page meets a <script>, browser will wait for this content to be parsed and executed. Page rendering and user interaction are completely blocked during this time. And the browser doesn’t start rendering anything on the page until the opening <body> tag is encountered. Considering these two facts, it is recommended to place all <script> tags as close to the bottom of the <body> tag as possible so as not to affect the download of the entire page.

<html>
<head>
  <title>Script Position</title>
  <link ref="stylesheet" type="text/css" href="stype.css">
</head>
<body>
  <p>hello world</p>
  ...
  <script type="text/javascript" src="file1.js"></script>
</body>
</html>

Grouping Scripts

It is recommended to concatenate JavsScript files together into a single file and then call that single file with a single <script> tag. The reason is that each HTTP request brings with it additional performance overhead, so downloading one 100 KB file will be faster than downloading four 25 KB files.

Nonblocking Scripts

Nonblocking script is to load the JavaScript source code after the page has finished loading. There are a few techniques for achieving this result.

  1. Deferred Scripts
    1. The defer attribute indicates that the script contained within the element is not going to modify the DOM and therefore execution can be safely deferred until a later point in time. (only in IE 4+ and Firefox 3.5+) Any <script> element marked with defer will not execute until after the DOM has been completely loaded, before the onload event handler is called. (DOM —> defer script —> window.onload)
    2. <script type="text/javascript" src="files1.js" defer></script>
  2. Dynamic Script Elements
  3. XMLHttpRequest Script Injection

Data Access

Data Types

There are four basic places from which data can be accessed in JavaScript.

  1. Literal values
    • JavaScript can represent strings, numbers, Booleans, objects, arrays, functions, regular expressions, and the special values null and undefined as literals.
  2. Variables
    • Any developer-defined location for storing data created by using the var keyword.
  3. Array items
    • A numerically indexed location within a JavaScript Array object.
  4. Object members
    • A string-indexed location within a JavaScript object.

The general trends remain the same across all browsers: literal value and local variable access tend to be faster than array item and object member access.

Data Scope

Every function in JavaScript is represented as an object – more specifically, as an instance of Function. Local variables are always the fastest to access inside of a function, whereas global variables will generally be the slowest. The reason is that global variables always exist in the last variable object of the execution context’s scope chain, so they are always the furthest away to resolve.

It’s advisable to use local variables whenever possible to improve performance in browsers without optimizing JavaScript engines. A good rule of thumb is to always store out-of-scope values in local variables if they are used more than once within a function. If you need to refer to a global variable many times, like this, window, document, etc. you can store the reference in a local variable and then use the local variable instead of the global.

DOM Scripting

The Document Object Model (DOM) is a language-independent application interface (API) for working with XML and HTML documents.

The more you access the DOM, the slower your code executes. Therefore, the general rule of thumb is this: touch the DOM lightly, and stay within ECMAScript as much as possible. Or you can clone existing DOM elements instead of creating new ones – in other words, using element.cloneNode() (where element is an existing node) instead of document.createElement().

Algorithms and Flow Control

Loops

There are four types of loop.

// Type 1
for (var i=0; i < 10; i++){
  //loop body
}
// Type 2
var i = 0;
while(i < 10){
 //loop body
 i++;
}
// Type 3
var i = 0;
do {
 //loop body
} while(i++ < 10);
// Type 4: The for-in loop is significantly slower than the others. 
for (var prop in object){
 //loop body
}

It’s recommended to avoid to the for-in loop unless your intent is to iterate over an unknown number of object properties. If you have a finite, known list of properties to iterate over, it is faster to use one of the other loop types and use a pattern such as this:

var props = ["prop1", "prop2"],
    i = 0;
while (i < props.length){
  process(object[props[i]);
}

Decreasing the work per iteration

//original loops
for (var i=0; i < items.length; i++){
  //process(items[i]);
}

To minimize property lookups, see this optimization:

for (var i=0, len=items.length; i < len; i++){
  process(items[i]);
}
// Or antoher way
for (var i=items.length; i--; ){
  process(items[i]);
}

Strings and Regular Expressions

Responsive Interface

Ajax

Advertisements