DHTML and JavaScript Performance Tuning

Using JavaScript

Strings

How you work with Strings can have big impact on the performance of you script. This is something that is not well known or practiced. If you haven't read this before, read carefully and remember well. This is important.

  1. Concatenate String Literals Instead of String Variables
  2. Concatenate With + Instead of +=

Concatenate String Literals Instead of String Variables

With String literals, the performance gain in Mozilla is exponential. By concatenating string literals, the resulting value is interpreted and assigned to s when the script is interpreted.

An equivalent benefit can occur in Mozilla when using a local variable that does not change in value.

Concatenate String Literals Instead of String Variables
Ease Effectiveness Overall Practicality
8
M IE S Op
10 5 1 ?
9

Demo ->

String Literal Concatenation

Concatenate With + Instead of +=

Concatenate With + Instead of +=
Ease Effectiveness Overall Practicality
8
M IE S Op
10 5 1 ?
9

The example uses the following variables:

var h = "hello "; // create a string (1).
var d = "drunken "; // create a string (2).
var w = "world "; // create a string. (3).
How many String objects are created in the example below?
var s = h; 
s += d; // create a new string "hello drunken" (4).
s += w; // create a new string "hello drunken world" (5).
s = h 
+d
+w; // created one new string for a total of four strings.
var s = "hello " + "drunken " + "world ";

Would assign "hello drunken world" to s.

See These Examples in Action

Each demo tests concatenation with a different type of variable

If you ran all three tests above, you probably realized that using a local variable and concatenating with + (not +=) is the fastest way to concatenate strings.

Next in this tutorial:

 

*AnimTree
*Tabs
*GlideMenus
*DragLib