04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 20: Best Practices<br />

};<br />

//set a timeout - fixed<br />

setTimeout(function(){<br />

alert(‘Hello world!’);<br />

}, 500);<br />

To increase the performance of your code, avoid using strings that need to be interpreted as JavaScript<br />

whenever possible.<br />

Other Performance Considerations<br />

There are a few other things to consider when evaluating the performance of your script. The following<br />

aren ’ t major issues, but they can make a difference when used frequently:<br />

❑<br />

❑<br />

❑<br />

Native methods are fast — Whenever possible, use a native method instead of one written in<br />

JavaScript. Native methods are written in compiled languages such as C or C++ and thus run<br />

much faster than those in JavaScript. The most often forgotten methods in JavaScript are the<br />

complex mathematical operations available on the Math object; these methods always run faster<br />

than any JavaScript equivalent for calculating sine, cosine, and so on.<br />

Switch statements are fast — If you have a complex series of if - else statements, converting it<br />

to a single switch statement can result in faster code. You can further improve the performance<br />

of switch statements by organizing the cases in the order of most likely to least likely.<br />

Bitwise operators are fast — When performing mathematical operations, bitwise operations are<br />

always faster than any Boolean or numeric arithmetic. Selectively replacing arithmetic<br />

operations with bitwise operations can greatly improve the performance of complex<br />

calculations. Operations such as modulus, logical AND, and logical OR are good candidates to<br />

be replaced with bitwise operations.<br />

Minimize Statement Count<br />

The number of statements in JavaScript code affects the speed with which the operations are performed.<br />

A single statement can complete multiple operations faster than multiple statements each performing a<br />

single operation. The task, then, is to seek out statements that can be combined, in order to decrease the<br />

execution time of the overall script. To do so, there are several patterns to look for.<br />

Multiple Variable Declarations<br />

One area in which developers tend to create too many statements is in the declaration of multiple<br />

variables. It ’ s quite common to see code declaring multiple variables using multiple var statements,<br />

such as the following:<br />

//four statements - wasteful<br />

var count = 5;<br />

var color = “blue”;<br />

var values = [1,2,3];<br />

var now = new Date();<br />

655

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!