views:

67

answers:

2

Just wondering if there is any advantage to using

private static const

instead of

private const

for private constants? Does this change if you have only one instance of the class or multiple? I suspect that there might be some small memory/performance advantage in using static if you have multiple instances of the class.

+4  A: 

private static const members are stored once per type.

private const members are stored once per instance.

So yes, you are saving some memory.

mmsmatt
thanks mmsmatt, that is what I suspected
danjp
at the cost of performance. see my answer for details.
back2dos
+5  A: 

As mmsmatt pointed out, they save a some memory. Usually this is not the best place to save memory however. You should rather worry about memory leaks, about efficient file formats and data representation in general.

A downside of static constants is that all global access is slower than local access. instance.ident outperforms Class.ident. Run this code to test:

package  {
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.utils.*;
    public class Benchmark extends Sprite {
        private static const delta:int = 0;
        private const delta:int = 0;        
        private var output:TextField;
        public function Benchmark() {
            setTimeout(doBenchmark, 1000);
            this.makeOutput();
        }
        private function doBenchmark():void {
            var i:int, start:int, sum:int, inst:int, cls:int;

            start = getTimer();
            sum = 0;
            for (i = 0; i < 100000000; i++) sum += this.delta;
            out("instance:", inst = getTimer() - start);

            start = getTimer();
            sum = 0;
            for (i = 0; i < 100000000; i++) sum += Benchmark.delta;
            out("class:", cls = getTimer() - start);

            out("instance is", cls/inst, "times faster");
        }   
        private function out(...args):void {
            this.output.appendText(args.join(" ") + "\n");
        }
        private function makeOutput():void {
            this.addChild(this.output = new TextField());
            this.output.width = stage.stageWidth;
            this.output.height = stage.stageHeight;
            this.output.multiline = this.output.wordWrap = true;
            this.output.background = true;          
        }       
    }
}
back2dos
thanks back2dos - that is a great example
danjp
What if the class does not definitely need to be instantiated? Maybe using the non-static approach could save memory in that case.
danyal