18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

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

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

Deployment Issues<br />

do {<br />

//do something here<br />

i++;<br />

} while (i < aValues.length);<br />

This code now runs faster than using the while loop, but it can be optimized further by reversing the loop:<br />

var i=aValues.length-1;<br />

do {<br />

//do something here<br />

i--;<br />

} while (i >= 0);<br />

You can also eliminate an extra statement by putting the decrement into the control statement directly:<br />

var i=aValues.length-1;<br />

do {<br />

//do something here<br />

} while (i-- >= 0);<br />

The loop has now been fully optimized for execution speed.<br />

Unroll your loops<br />

Instead of using loops that execute one statement each time through, you can unroll these loops to run<br />

multiple statements. Consider the following simple for loop:<br />

var aValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];<br />

var iSum = 0;<br />

for (var i=0; i < aValues.length; i++) {<br />

iSum += aValues[i];<br />

}<br />

This loop body executes 20 times, each time adding to the variable iSum. This is a fairly simple operation,<br />

so it’s possible to unroll this operation and execute it several times within the for loop:<br />

var aValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];<br />

var iSum = 0;<br />

for (var i=0; i < aValues.length; i++) {<br />

iSum += aValues[i];<br />

i++;<br />

iSum += aValues[i];<br />

i++;<br />

iSum += aValues[i];<br />

i++;<br />

585

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

Saved successfully!

Ooh no, something went wrong!