Any advantage to using 'static' on private consts?
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 开发者_如何学JAVAadvantage in using static
if you have multiple instances of the class.
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;
}
}
}
private static const
members are stored once per type.
private const
members are stored once per instance.
So yes, you are saving some memory.
It depends on the case.
As stated, the static will be once per type and non-static will be once per instance, so it depends on how many instances you are going to have.
I say that because if you have a component that is only instantiated once at a time (like a prompt pop-up) and you fully dispose of it from the memory after, then it means having as static you are using unnecessary memory since it'll never go away that static variable. If it's something you'll have multiple instances of (like particles or multiple windows) then yes it's better to use static because they'll share the same variable.
精彩评论