我听说代码放在构造里要比放在构造之外的执行速度慢些。所以,我决定做一个测试,看看构造有多慢? 这项测试的方法是:在构造函数和非构造函数中运行一些代价较高的代码。并没有考虑此代码完全相同,只是确保代码直接地在构造函数中工作,而不是间接地通过函数调用。通常你应该考虑到这点,但在这里它会破坏测试的目的。 我选择做一个大量循环累计的工作。计算的结果是没有意义的,但是用公有变量存储该值是为了确保编辑器将不会优化内循环,尽管它可能无论如何也不会做优化。 事不宜迟,下面是测试用的代码:
- package
- {
- import flash.text.*;
- import flash.events.*;
- import flash.display.*;
- public class ConstructorTest extends Sprite
- {
- private var __logger:TextField = new TextField();
- public function ConstructorTest()
- {
- __logger.autoSize = TextFieldAutoSize.LEFT;
- addChild(__logger);
- // Do the next frame so we don't test code in functions called FROM
- // a constructor, just in case.
- addEventListener(Event.ENTER_FRAME, onEnterFrame);
- }
- private function onEnterFrame(ev:Event): void
- {
- // We just wanted to do the test once
- removeEventListener(Event.ENTER_FRAME, onEnterFrame);
- // Constructor test
- var tester:Tester = new Tester(log);
- // Non-constructor test
- tester.init(log);
- }
- private function log(msg:*): void
- {
- __logger.appendText(msg + "/n");
- }
- }
- }
- import flash.utils.*;
- class Tester
- {
- public var total:int;
- public function Tester(log:Function)
- {
- var total:int = 0;
- var beforeTime:int = getTimer();
- for (var i:int; i < 50000; ++i)
- {
- for (var j:int = 0; j < i; ++j)
- {
- total += j;
- }
- }
- log("constructor time: " + (getTimer()-beforeTime));
- this.total = total;
- }
- public function init(log:Function): void
- {
- var total:int = 0;
- var beforeTime:int = getTimer();
- for (var i:int; i < 50000; ++i)
- {
- for (var j:int = 0; j < i; ++j)
- {
- total += j;
- }
- }
- log("init() time: " + (getTimer()-beforeTime));
- this.total = total;
- }
- }
复制代码
Intel Core 2 Duo 2.2Ghz二级缓存2GB,Mac OS X 10.6 (Snow Leopard)获得的输出结果: 构造时间:3446; init()时间:3437 Intel Core 2 Duo 3.0Ghzz二级缓存2GB,Windows上获得的结果: 构造时间:2518; init()时间:2519 从整体规模上看这些结果看上去很相近。虽然init()函数有时会比构造要快一丁点,但的确是微乎其微。除非你把重要工作几乎全在构造中完成。否则我不认为你有什么可担心的。 个人的看法好像在一篇文章上看到说是JIT未对构造函数进行优化造成这个现象,可是为什么不优化呢? |