2012-03-15 64 views
0

我正在寫一個動畫循環,所以試圖優化速度。這涉及到犧牲很多可讀性,但是我想知道它是否會在某種程度上變得適得其反。例如,我可能會開始像這樣的東西:Javascript:複雜的值引用是否會影響執行速度?

var Animation = Animations[Current_Animation]; 
var Sequence = Animation.Sequences[Current_Sequence]; 
var Action = Sequence.Actions[Current_Action]; 
if (Action.Repeat_Count != Action.Repeat_End) Sequence.Index--; 

但是,當我刪除了優化的外部變量,它出來與真正大規模的引用:

if (Animations[Current_Animation].Sequences[Current_Sequence].Actions 
[Animations[Current_Animation].Sequences[Current_Sequence].Index].Repeat_Count 
!= Animations[Current_Animation].Sequences[Current_Sequence].Actions 
[Animations[Current_Animation].Sequences[Current_Sequence].Index].Repeat_End) 
Animations[Current_Animation].Sequences[Current_Sequence].Index--; 

我的循環,現在滿是這樣的怪物。所以我想知道如果解釋器不得不停止排序所有這些可能實際上比使用佔位符慢。還是它自動地知道這一切意味着什麼,而不使用任何額外的CPU?

謝謝!

+0

現代瀏覽器在這方面可能有所改進,但避免不必要的財產查詢仍然是一件好事。此外,重複'動畫[Current_Animation] .Sequences [Current_Sequence]'一遍又一遍的感覺是錯誤的;) – 2012-03-15 15:07:05

回答

1

你短的代碼更易讀上我用,更何況,如果這是客戶端JS下載時間會少具有較少的字節較短任何JS引擎速度更快!

但是,您應該使用var關鍵字,以便所有變量都不在全局範圍內。我相信你沒有理由在上面的代碼中將Animation,SequenceAction設爲全局變量,因爲它們實際上只是臨時變量,但由於它們沒有顯式聲明爲當前函數作用域的局部變量,他們自動全球化。

var Animation = Animations[Current_Animation]; 
var Sequence = Animation.Sequences[Current_Sequence]; 
var Action = Sequence.Actions[Current_Action]; 
if (Action.Repeat_Count != Action.Repeat_End) Sequence.Index--; 
0

每一個talk given at SXSW (slide 40)這一週,它在幾乎任何廣泛使用的瀏覽器的任何顯著方式not impacting on performance

但是,使用引用(第一個代碼示例)的版本更容易閱讀,IMO。如PaulP.R.O所述。它需要通過var進行適當的範圍控制,但它(更確切地說主觀上)是更好的代碼。

相關問題