04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 20: Best Practices<br />

(continued)<br />

do {<br />

process(values[i++]);<br />

process(values[i++]);<br />

process(values[i++]);<br />

process(values[i++]);<br />

process(values[i++]);<br />

process(values[i++]);<br />

process(values[i++]);<br />

process(values[i++]);<br />

} while (--iterations > 0);<br />

In this implementation, the leftover count that wouldn ’ t have been handled in the loop when simply<br />

dividing by 8 is handled in an initial loop. Once those extra items are processed, execution continues in<br />

the main loop that calls process() eight times. This approach is almost 40% faster than the original<br />

Duff ’ s device implementation.<br />

Unrolling loops can yield big savings for large datasets but may not be worth the extra effort for small<br />

datasets. The trade - off is that it takes more code to accomplish the same task, which is typically not<br />

worth it when large datasets aren ’ t being processed.<br />

Avoid Double Interpretation<br />

Double interpretation penalties exist when JavaScript code tries to interpret JavaScript code. This<br />

situation arises when using the eval() function or the Function constructor, or when using<br />

setTimeout() with a string argument. Here are some examples:<br />

//evaluate some code - AVOID!!<br />

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

//create a new function - AVOID!!<br />

var sayHi = new Function(“alert(‘Hello world!’)”);<br />

//set a timeout - AVOID!!<br />

setTimeout(“alert(‘Hello world!’)”, 500);<br />

In each of these instances, a string containing JavaScript code has to be interpreted. This can ’ t be done<br />

during the initial parsing phase because the code is contained in a string, which means a new parser has<br />

to be started while the JavaScript code is running to parse the new code. Instantiating a new parser<br />

has considerable overhead, so the code runs slower than if it were included natively.<br />

There are workarounds for all of these instances. It ’ s rare that eval() is absolutely necessary, so try to<br />

avoid it whenever possible. In this case, the code could just be included inline. For the Function<br />

constructor, the code can be rewritten as a regular function quite easily, and the setTimeout() call can<br />

pass in a function as the first argument. Here are some examples:<br />

//fixed<br />

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

//create a new function - fixed<br />

var sayHi = function(){<br />

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

654

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

Saved successfully!

Ooh no, something went wrong!