javascript - Declaring new variables or using references in functions? -
when defining methods class, better use members or assigning them new variable make faster? imagine, instance in javascript following method:
square: function() { var x = this.x; x *= x; return x; }
or
square: function() { this.x *= this.x; return this.x; }
in general, difference in speed negligible, meaning premature optimization, should avoided in favor of using whatever method more maintainable.
however, in particular case there major difference in functionality between 2 square
methods, shown below.
var = { x: 2, square: function() { var x = this.x; x *= x; return x; } } console.log('result of a.square():', a.square()); //output 4 console.log('after square, a.x is:', a.x); //output 2 var b = { x: 2, square: function() { this.x *= this.x; return this.x; } } console.log('result of b.square():', b.square()); //output 4 //the difference here: b.x 4 while a.x still 2 console.log('after square, b.x is:', b.x); //output 4
the first square
method not update this.x
, second method will. use whichever version matches intent. simplified versions of each method below, after eliminating premature optimization. gain in maintainability clear.
first version (does not update this.x
):
square: function() { return this.x * this.x; }
second version (does update this.x
):
square: function() { return this.x *= this.x; }
Comments
Post a Comment