我有一个嵌套了好几层的对象,我多次引用它。创建和设置对该对象的引用是否更快或是否重要?
上下文我听说创建本地引用会更快。这是多年前的一个 Visual Basic 项目。但这是Flash。并且输出是一个 SWF / 字节码。并且编译器可以查看该引用并执行我正在执行的操作,这样就不必每次都查找该对象。
例如:
public function doStuff():void {
Model.instance.view1.button1 = button1;
Model.instance.view1.button2 = button2;
Model.instance.view1.button3 = button3;
Model.instance.view1.button4 = button4;
Model.instance.view1.button5 = button5;
Model.instance.view1.button6 = button6;
// more fake code referencing more something.something.something like things
for (var i:int;i<something.something.something.length;i++) {
var result:Object = Controller.staticMethod(button1);
var result2:Object = Controller.staticMethod(button1);
}
}
对比:
public function doStuff():void {
var view1:View = Model.instance.view1;
view1.button1 = button1;
view1.button2 = button2;
view1.button3 = button3;
view1.button4 = button4;
view1.button5 = button5;
view1.button6 = button6;
}
.
接受 Baris 的建议,我自己测试了它。下面是结果(尽管我不知道如何将它们解释为实际差异,即“方法 1 比方法 2 快 0.000001”)。
结果
测试 1
var instance:Model = Model.instance;
var startTime:int = getTimer();
for(var i:int = 0; i<10000000; i++){
instance.url = "";
}
trace(getTimer()-startTime); // 826, 929, 823
var startTime:int = getTimer();
for(var i:int = 0; i<10000000; i++){
Model.instance.url = "";
}
trace(getTimer()-startTime); // 3483, 3976, 3539
测试 2
var instance:Model = Model.instance;
var localLogo:BitmapImage = Model.instance.logo;
var startTime:int = getTimer();
for(var i:int = 0; i<10000000; i++){
localLogo = logo;
}
trace(getTimer()-startTime); // 2070, 2083, 2110
var startTime:int = getTimer();
for(var i:int = 0; i<10000000; i++){
instance.logo = logo;
}
trace(getTimer()-startTime); // 2028, 2509, 2154