↑

Main Page

# Remember Computer Science 101

Remember Computer Science 101

A lot of the basics relating to optimization of code in other programming languages also apply to

JavaScript. Because JavaScript borrows syntax and statements so heavily from C, Java, and Perl, the

same techniques used to optimize code in those languages can also be used in JavaScript. The techniques

presented in this section have been written about in books and articles such as Koushik Ghosh’s

“Writing Efficient C and C Code Optimization” (available online at

http://www.codeproject.com/

cpp/C___Code_Optimization.asp

). In this article, Ghosh has compiled a list of the most popular code

optimization techniques for C, many of which apply to JavaScript as well.

Choosing the right algorithm

When programming, choosing the right algorithm is as important as anything you do. The less complex

the algorithm, the faster your code runs. To measure the complexity of algorithms, computer scientists

use Big O notation. Big O notation consists of the letter

O

defined as a function with certain arguments.

The simplest algorithm is a constant value, represented as O(1). Retrieving a constant value is an extremely

fast process. Constant values are made up of both true constants, such as the number 5, as well as values

stored in variables. Consider the following example:

var iFive = 5;

var iSum = 10 + iFive;

alert(iSum);

This code retrieves three constant values. The first two are the number 10 and the variable

iFive

in the

second line. Then, in Line 3, the value of

iSum

is retrieved; this is also a constant value. These three con-

stant retrievals take very little time because of their simplicity.

All values stored in arrays are also constant values, so the following code uses only the constant value

algorithm:

var aNumbers = [5,10];

var iSum = aNumbers[0] + aNumbers[1];

alert(iSum);

In this code the array

aNumbers

is used to store the numbers to be added. Both

aNumbers[0]

and

aNumbers[1]

are constant value retrievals, so the total number of O(1) algorithms in this code is

also three.

The next algorithm is called linear, represented by O(

n

). This algorithm is used in simple searches, where

an array is searched through, item by item, until a result is found. The following is an example of a lin-

ear algorithm:

for (var i=0; i < aNumbers.length; i++) {

if (aNumbers[i] == 5) {

alert(“Found 5”);

break;

}

}

582

Chapter 19

22_579088 ch19.qxd 3/28/05 11:43 AM Page 582

Free JavaScript Editor
Ajax Editor

©

↓