Reuse objects rather than recreate
suggest changeExample A
let i,a,b,len;
a = {x:0,y:0}
function test(){ // return object created each call
return {x:0,y:0};
}
function test1(a){ // return object supplied
a.x=0;
a.y=0;
return a;
}
for(i = 0; i < 100; i ++){ // Loop A
b = test();
}
for(i = 0; i < 100; i ++){ // Loop B
b = test1(a);
}
Loop B reuses one object. Loop A allocates a new object on every call and then drops it. That difference is allocation, not a fixed speedup. A multiple such as “4 times” was one old timing and is not a property of the language. Reusing the object also means later code sees the mutated values.
Example B
let i,a,b,len;
a = {x:0,y:0}
function test2(a){
return {x : a.x * 10, y : a.y * 10};
}
function test3(a){
a.x= a.x * 10;
a.y= a.y * 10;
return a;
}
for(i = 0; i < 100; i++){ // Loop A
b = test2({x : 10, y : 10});
}
for(i = 0; i < 100; i++){ // Loop B
a.x = 10;
a.y = 10;
b = test3(a);
}
Loop B again avoids allocating a fresh object. The old “5 times” figure is not a portable result. test3 mutates its argument, so the caller must reset a before the next call, as this loop does.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents