Main Page

Execution time

Use array and object literals
The concept of array literals was touched on briefly earlier in the book. To review, the following two
lines are equivalent:
var aTest = new Array;
var aTest = [];
The second line uses an array literal, which is just as valid as the first line. But as is very apparent, the
second line uses fewer characters (and thus bytes). It’s good practice to always use array literals when
creating arrays.
Likewise, object literals can be used to save a lot of space as well. The following two lines are equivalent,
but the one using an object literal uses fewer bytes:
var oTest = new Object;
var oTest = {};
This also works if you are creating a generic object with a few properties, such as this:
var oFruit = new Object;
oFruit.color = “red”; = “apple”;
The previous code can be rewritten using an object literal as the following:
var oFruit = { color: “red”, name: “apple” };
This example uses an object literal to assign the two properties
, and in doing so, saves a
lot of bytes.
Execution time
The second part of overall JavaScript performance is the amount of time it takes a script to run. Because
JavaScript is an interpreted language, the speed of execution is significantly slower than compiled
Geoffrery Fox of Syracuse University wrote an online seminar entitled “JavaScript Performance Issues”
(available at
), in which he described JavaScript’s performance relative to other well-known program-
ming languages. According to Fox, JavaScript is:
5000 times slower than compiled C
100 times slower than interpreted Java
10 times slower than interpreted Perl
Keeping this in mind, you can do some simple things to improve the performance of your JavaScript
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 578

JavaScript EditorFree JavaScript Editor     Ajax Editor