雖然有關代碼提示和錯誤檢查其他答案點是準確的,我想,以解決有關性能的要求。事實並非如此。理論上,強類型允許編譯器生成更接近本機的代碼。儘管目前的VM,這種優化不會發生。在這裏和那裏,AS3編譯器將採用整數指令而不是浮點指令。否則,類型指示器在運行時不會產生太大影響。
例如,請考慮下面的代碼:
function hello():String {
return "Hello";
}
var s:String = hello() + ' world';
trace(s);
我這裏還有的AVM2操作碼從它產生的:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 4 0 ; call hello()
pushstring 12 ; push ' world' onto stack
add ; concatenate the two
initproperty 5 ; save it to var s
findpropstrict 7 ; look up trace
getlocal_0 ; push this onto stack
getproperty 5 ; look up var s
callpropvoid 7 1 ; call trace
returnvoid
現在,如果我去掉類型的指標,我得到以下:
getlocal_0
pushscope
getlocal_0
getlocal_0
callproperty 3 0
pushstring 11
add
initproperty 4
findpropstrict 6
getlocal_0
getproperty 4
callpropvoid 6 1
returnvoid
完全一樣,除了所有的名字索引都少一個'String'no更長的時間出現在常量表中。
我不想阻止人們使用強打字。一個人不應該期待性能方面的奇蹟。
編輯:如果有人有興趣,我已經把我的AS3字節碼反彙編在線:
http://flaczki.net46.net/codedump/
,以便它現在取消引用操作數我已經改善它。
這是一個很不好的例子。它比較動態對象與封閉對象的初始化。性能差異與強/弱打字無關。 – cleong 2012-08-14 23:08:24