Using . or [ ] to access Object properties - what's the difference?

你离开我真会死。 提交于 2019-12-04 03:23:23

问题


What is the difference between the code (i) and (ii) written below ?

(i)

var obj:Object = new Object();
obj.attribute = value ;

(ii)

var obj:Object = new Object();
obj["key"] = value;

Are there any run-time implications if I write this :

var obj:Object = new Object();
obj.somekey = value1 ;
obj["someKey"] = value2 ;

Please explain.


回答1:


The difference is in the lookup mechanism: If you use the dot syntax, the compiler will know at compile time that you are accessing a property of that object. If you use the bracket syntax, the actual lookup of the property is done at runtime, and there will have to be more type checking - after all, you could compose the key string dynamically, the value could change, or you could even be calling a function instead of a variable, etc.

The result is a significant difference in performance: Bracket syntax takes about three times as long to execute as dot syntax.

Here's a little speed test to illustrate my point:

var start : int = getTimer();

var obj:Object = { something : "something" };

for (var i : int = 0; i < 100000000; i++) {
    var n:String = obj.something;
}

trace ("Time with dot syntax: "+(getTimer() - start));

start = getTimer();

for (i = 0; i < 100000000; i++) {
    var o:String = obj["something"];
}

trace ("Time with bracket syntax: "+(getTimer() - start));

If the two were the same, except for notation, they should take exactly the same amount of time. But as you can see, this is not the case. On my machine:

Time with dot syntax:      3937
Time with bracket syntax:  9857


来源:https://stackoverflow.com/questions/9097664/using-or-to-access-object-properties-whats-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!