Therefore, consider some alternatives.
Avoiding Nested Properties
Aim to keep the levels of dot hierarchy small. Nested properties, such as document.property
.property.property , cause the biggest performance problems and should be avoided or accessed
as few times as possible.
// Inefficient
m.n.o.p.doThis();
m.n.o.p.doThat();
// More efficient
var d = m.n.o.p;
d.doThis();
d.doThat();
Accessing a Named Object
If you access a named object, it is more efficient to use getElementById() rather than access it via dot
notation. For example, compare the following:
// Inefficient
document.form1.addressLine1.value
// More efficient
document.getElementById( ???addressLine1??™ ).value;
Property Lookups Inside Loops
When accessing a property inside of a loop, it is much better practice to cache the property reference
first, and then access the variable inside of the loop. For example, compare the following:
// Inefficient
for(i = 0; i < 10; i++) {
var v = document.object.property(i);
var y = myCustonObject.property(i);
// do something
}
// More efficient
var p = document.object.property;
var cp = myCustonObject.property(i);
for(i = 0; i < 10; i++) {
var v= p(i);
var y=cp(i);
// do something
}
Chapter 9: Bandwidth and Performance Optimizations
218
Here ??™ s another example of using the length property of an object in the condition of a for loop:
// Inefficient
for (i=0;i < myObject.
Pages:
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253