使用。或[]访问对象属性 - 有什么区别? [英] Using . or [ ] to access Object properties - what's the difference?

查看:164
本文介绍了使用。或[]访问对象属性 - 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间的code(i)及(ii)中写的?

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

(一)

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

(ⅱ)

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 ;

请解释一下。

推荐答案

所不同的是,在查找机制:如果您使用点语法,编译器将在编译时知道您访问该对象的属性。如果您使用括号语法,该财产的实际查找是在运行,而且将有更多的类型检查 - 毕竟,你可以动态地组合密钥字符串,其值可以改变,或者你甚至可以调用一个函数,而不是一个变量,等等。

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

这篇关于使用。或[]访问对象属性 - 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆