2014-12-06 80 views
1

爲類定義方法時,最好自己使用成員還是將它們分配給新變量使其更快?試想一下,比如在JavaScript下面的方法:聲明新變量或在函數中使用引用?

square: function() { 
    var x = this.x; 
    x *= x; 
    return x; 
} 

square: function() { 
    this.x *= this.x; 
    return this.x; 
} 
+4

您是變異的'this.x'值的第二種情況。在第一種情況下,你不是。 – 2014-12-06 02:36:11

+0

第一個不會比單行更好:'return this.x * this.x;'?這避免了創建額外的變量,並且不執行任何分配。 (正如你已經指出的,你的第二個版本不會做同樣的事情,所以兩者之間的比較沒有意義。) – nnnnnn 2014-12-06 02:47:34

回答

0

在一般情況下,在速度上的差異幾乎總是可以忽略不計,這意味着這是一個premature optimization,這應該避免青睞使用任何方法都更易於維護。

但是,在您的具體情況下,兩個square方法之間的功能存在主要差異,如下所示。

var a = { 
 
    x: 2, 
 
    square: function() { 
 
     var x = this.x; 
 
     x *= x; 
 
     return x; 
 
    } 
 
} 
 

 
console.log('Result of a.square():', a.square()); //Output is 4 
 
console.log('After square, a.x is:', a.x); //Output is 2 
 

 
var b = { 
 
    x: 2, 
 
    square: function() { 
 
     this.x *= this.x; 
 
     return this.x; 
 
    } 
 
} 
 

 
console.log('Result of b.square():', b.square()); //Output is 4 
 

 
//The difference is here: b.x will be 4 while a.x is still 2 
 
console.log('After square, b.x is:', b.x); //Output is 4

第一square方法將不會更新this.x,但第二個方法將。使用符合您意圖的版本。在消除了過早優化之後,每種方法的簡化版本如下。可維護性的增益很明顯。

第一個版本(不更新this.x):

square: function() { 
    return this.x * this.x; 
} 

第二個版本(不更新this.x):

square: function() { 
    return this.x *= this.x; 
}