length;i++) {
// Do something
}
// More efficient
for (i=0,var j=myObject.length;i < j;i++) {
// Do something
}
Similarly, if you are using arrays inside of loops and using its length as a conditional, you want to
assign its length to a variable rather than evaluating at each pass. Check this out:
// Inefficient
myArray = new Array();
for (i=0;i < myArray.length;i++) {
// Do something
}
// More efficient
myArray = new Array();
len = myArray.length;
for (i=0;i < len;i++) {
// Do something
}
String Concatenation
Another traditional problem area in JavaScript is string concatenation. In general, you should try to
avoid an excessive number of concatenations and an excessively large string that you are appending to.
For example, suppose you are trying to construct a table in code and then write out the code to the
document once you are finished. The stringTable() function in the following code is less efficient than
the second function intermStringTable() , because the latter uses an intermediate string variable row
as a buffer in the for loop.
< html >
< script type=???text/javascript??? language=???javascript??? >
function stringTable() {
var start = new Date().getTime();
var buf = ??? < table > ???;
for (var i=0; i < 10000;i++){
buf += ??? < tr > ???;
for (var j=0;j < 40;j++){
buf += ??? < td > < i > ??? + ???content??? + ??? < /i > < /td > ???;
}
buf += ??? < /tr > ???;
}
buf += ??? < /table > ???;
var duration = new Date().
Pages:
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254